Adding guard PIP
[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.FileInputStream;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.io.InputStream;
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.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.junit.ClassRule;
48 import org.junit.FixMethodOrder;
49 import org.junit.Test;
50 import org.junit.rules.TemporaryFolder;
51 import org.junit.runners.MethodSorters;
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.pdp.xacml.application.common.OnapOperationsHistoryDbao;
58 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
59 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.yaml.snakeyaml.Yaml;
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("onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))
218             .isTrue();
219         assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))
220             .isFalse();
221         assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.MinMax", "1.0.0")).isTrue();
222         assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.MinMax", "1.0.1")).isFalse();
223         assertThat(service.canSupportPolicyType("onap.foo", "1.0.1")).isFalse();
224     }
225
226     @Test
227     public void test2NoPolicies() throws CoderException {
228         LOGGER.info("**************** Running test2 ****************");
229         requestAndCheckDecision(requestVfCount1,PERMIT);
230     }
231
232     @Test
233     public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException {
234         LOGGER.info("**************** Running test3 ****************");
235         //
236         // Now load the vDNS frequency limiter Policy - make sure
237         // the pdp can support it and have it load
238         // into the PDP.
239         //
240         try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml")) {
241             //
242             // Have yaml parse it
243             //
244             Yaml yaml = new Yaml();
245             Map<String, Object> toscaObject = yaml.load(is);
246             //
247             // Load the policies
248             //
249             service.loadPolicies(toscaObject);
250         }
251         //
252         // Zero recent actions: should get permit
253         //
254         requestAndCheckDecision(requestVfCount1,PERMIT);
255         //
256         // Add entry into operations history DB
257         //
258         insertOperationEvent(requestVfCount1);
259         //
260         // Only one recent actions: should get permit
261         //
262         requestAndCheckDecision(requestVfCount1,PERMIT);
263         //
264         // Add entry into operations history DB
265         //
266         insertOperationEvent(requestVfCount1);
267         //
268         // Two recent actions, more than specified limit of 2: should get deny
269         //
270         requestAndCheckDecision(requestVfCount1,DENY);
271     }
272
273     @Test
274     public void test4MinMax() throws CoderException, FileNotFoundException, IOException {
275         LOGGER.info("**************** Running test4 ****************");
276         //
277         // Now load the vDNS min max Policy - make sure
278         // the pdp can support it and have it load
279         // into the PDP.
280         //
281         try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml")) {
282             //
283             // Have yaml parse it
284             //
285             Yaml yaml = new Yaml();
286             Map<String, Object> toscaObject = yaml.load(is);
287             //
288             // Load the policies
289             //
290             service.loadPolicies(toscaObject);
291         }
292         //
293         // vfcount=1 below min of 2: should get a Deny
294         //
295         requestAndCheckDecision(requestVfCount1, DENY);
296         //
297         // vfcount=3 between min of 2 and max of 5: should get a Permit
298         //
299         requestAndCheckDecision(requestVfCount3, PERMIT);
300         //
301         // vfcount=6 above max of 5: should get a Deny
302         //
303         requestAndCheckDecision(requestVfCount6,DENY);
304         //
305         // Add two entry into operations history DB
306         //
307         insertOperationEvent(requestVfCount1);
308         insertOperationEvent(requestVfCount1);
309         //
310         // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
311         //
312         requestAndCheckDecision(requestVfCount3, DENY);
313         //
314         // vfcount=6 above max of 5: should get a Deny
315         //
316         requestAndCheckDecision(requestVfCount6, DENY);
317     }
318
319     @Test
320     public void test5MissingFields() throws FileNotFoundException, IOException {
321         LOGGER.info("**************** Running test5 ****************");
322         //
323         // Most likely we would not get a policy with missing fields passed to
324         // us from the API. But in case that happens, or we decide that some fields
325         // will be optional due to re-working of how the XACML policies are built,
326         // let's add support in for that.
327         //
328         try (InputStream is = new FileInputStream("src/test/resources/guard.policy-minmax-missing-fields1.yaml")) {
329             //
330             // Have yaml parse it
331             //
332             Yaml yaml = new Yaml();
333             Map<String, Object> toscaObject = yaml.load(is);
334             //
335             // Load the policies
336             //
337             service.loadPolicies(toscaObject);
338             //
339             // We can create a DecisionRequest on the fly - no need
340             // to have it in the .json files
341             //
342             DecisionRequest request = new DecisionRequest();
343             request.setOnapName("JUnit");
344             request.setOnapComponent("test5MissingFields");
345             request.setRequestId(UUID.randomUUID().toString());
346             request.setAction("guard");
347             Map<String, Object> guard = new HashMap<>();
348             guard.put("actor", "FOO");
349             guard.put("recipe", "bar");
350             guard.put("vfCount", "4");
351             Map<String, Object> resource = new HashMap<>();
352             resource.put("guard", guard);
353             request.setResource(resource);
354             //
355             // Ask for a decision - should get permit
356             //
357             DecisionResponse response = service.makeDecision(request);
358             LOGGER.info("Looking for Permit Decision {}", response);
359             assertThat(response).isNotNull();
360             assertThat(response.getStatus()).isNotNull();
361             assertThat(response.getStatus()).isEqualTo("Permit");
362             //
363             // Try a deny
364             //
365             guard.put("vfCount", "10");
366             resource.put("guard", guard);
367             request.setResource(resource);
368             response = service.makeDecision(request);
369             LOGGER.info("Looking for Deny Decision {}", response);
370             assertThat(response).isNotNull();
371             assertThat(response.getStatus()).isNotNull();
372             assertThat(response.getStatus()).isEqualTo("Deny");
373         }
374     }
375
376     @SuppressWarnings("unchecked")
377     private void insertOperationEvent(DecisionRequest request) {
378         //
379         // Get the properties
380         //
381         Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
382         assertThat(properties).isNotNull();
383         //
384         // Add an entry
385         //
386         OnapOperationsHistoryDbao newEntry = new OnapOperationsHistoryDbao();
387         newEntry.setActor(properties.get("actor").toString());
388         newEntry.setOperation(properties.get("recipe").toString());
389         newEntry.setClName(properties.get("clname").toString());
390         newEntry.setOutcome("SUCCESS");
391         newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
392         newEntry.setEndtime(Date.from(Instant.now()));
393         newEntry.setRequestId(UUID.randomUUID().toString());
394         newEntry.setTarget(properties.get("target").toString());
395         em.getTransaction().begin();
396         em.persist(newEntry);
397         em.getTransaction().commit();
398     }
399
400     @AfterClass
401     public static void cleanup() throws Exception {
402         em.close();
403     }
404 }