Test decision from main entry
[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.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
58 import org.onap.policy.pdp.xacml.application.common.OnapOperationsHistoryDbao;
59 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
60 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
61 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import org.yaml.snakeyaml.Yaml;
65
66 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
67 public class GuardPdpApplicationTest {
68
69     private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
70     private static Properties properties = new Properties();
71     private static File propertiesFile;
72     private static XacmlApplicationServiceProvider service;
73     private static DecisionRequest requestVfCount1;
74     private static DecisionRequest requestVfCount3;
75     private static DecisionRequest requestVfCount6;
76     private static StandardCoder gson = new StandardCoder();
77     private static EntityManager em;
78     private static final String DENY = "Deny";
79     private static final String PERMIT = "Permit";
80
81     @ClassRule
82     public static final TemporaryFolder policyFolder = new TemporaryFolder();
83
84     /**
85      * Copies the xacml.properties and policies files into
86      * temporary folder and loads the service provider saving
87      * instance of provider off for other tests to use.
88      */
89     @BeforeClass
90     public static void setUp() throws Exception {
91         LOGGER.info("Setting up class");
92         //
93         // Setup our temporary folder
94         //
95         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
96         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
97                 properties, myCreator);
98         //
99         // Load service
100         //
101         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
102                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
103         //
104         // Find the guard service application and save for use in all the tests
105         //
106         StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
107         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
108         while (iterator.hasNext()) {
109             XacmlApplicationServiceProvider application = iterator.next();
110             //
111             // Is it our service?
112             //
113             if (application instanceof GuardPdpApplication) {
114                 //
115                 // Should be the first and only one
116                 //
117                 assertThat(service).isNull();
118                 service = application;
119             }
120             strDump.append(application.applicationName());
121             strDump.append(" supports ");
122             strDump.append(application.supportedPolicyTypes());
123             strDump.append(System.lineSeparator());
124         }
125         LOGGER.info("{}", strDump);
126         //
127         // Tell it to initialize based on the properties file
128         // we just built for it.
129         //
130         service.initialize(propertiesFile.toPath().getParent());
131         //
132         // Load Decision Requests
133         //
134         requestVfCount1 = gson.decode(
135                 TextFileUtils.getTextFileAsString(
136                     "../../main/src/test/resources/decisions/decision.guard.vfCount.1.input.json"),
137                     DecisionRequest.class);
138         requestVfCount3 = gson.decode(
139                 TextFileUtils.getTextFileAsString(
140                     "../../main/src/test/resources/decisions/decision.guard.vfCount.3.input.json"),
141                     DecisionRequest.class);
142         requestVfCount6 = gson.decode(
143                 TextFileUtils.getTextFileAsString(
144                     "../../main/src/test/resources/decisions/decision.guard.vfCount.6.input.json"),
145                     DecisionRequest.class);
146         //
147         // Create EntityManager for manipulating DB
148         //
149         em = Persistence.createEntityManagerFactory(
150                 GuardPdpApplicationTest.properties.getProperty("historydb.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 OnapOperationsHistoryDbao").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(2);
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("onap.foo", "1.0.1"))).isFalse();
228     }
229
230     @Test
231     public void test2NoPolicies() throws CoderException {
232         LOGGER.info("**************** Running test2 ****************");
233         requestAndCheckDecision(requestVfCount1,PERMIT);
234     }
235
236     @Test
237     public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
238         XacmlApplicationException {
239         LOGGER.info("**************** Running test3 ****************");
240         //
241         // Now load the vDNS frequency limiter Policy - make sure
242         // the pdp can support it and have it load
243         // into the PDP.
244         //
245         try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml")) {
246             //
247             // Have yaml parse it
248             //
249             Yaml yaml = new Yaml();
250             Map<String, Object> toscaObject = yaml.load(is);
251             //
252             // Load the policies
253             //
254             service.loadPolicies(toscaObject);
255         }
256         //
257         // Zero recent actions: should get permit
258         //
259         requestAndCheckDecision(requestVfCount1,PERMIT);
260         //
261         // Add entry into operations history DB
262         //
263         insertOperationEvent(requestVfCount1);
264         //
265         // Only one recent actions: should get permit
266         //
267         requestAndCheckDecision(requestVfCount1,PERMIT);
268         //
269         // Add entry into operations history DB
270         //
271         insertOperationEvent(requestVfCount1);
272         //
273         // Two recent actions, more than specified limit of 2: should get deny
274         //
275         requestAndCheckDecision(requestVfCount1,DENY);
276     }
277
278     @Test
279     public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
280         LOGGER.info("**************** Running test4 ****************");
281         //
282         // Now load the vDNS min max Policy - make sure
283         // the pdp can support it and have it load
284         // into the PDP.
285         //
286         try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml")) {
287             //
288             // Have yaml parse it
289             //
290             Yaml yaml = new Yaml();
291             Map<String, Object> toscaObject = yaml.load(is);
292             //
293             // Load the policies
294             //
295             service.loadPolicies(toscaObject);
296         }
297         //
298         // vfcount=1 below min of 2: should get a Deny
299         //
300         requestAndCheckDecision(requestVfCount1, DENY);
301         //
302         // vfcount=3 between min of 2 and max of 5: should get a Permit
303         //
304         requestAndCheckDecision(requestVfCount3, PERMIT);
305         //
306         // vfcount=6 above max of 5: should get a Deny
307         //
308         requestAndCheckDecision(requestVfCount6,DENY);
309         //
310         // Add two entry into operations history DB
311         //
312         insertOperationEvent(requestVfCount1);
313         insertOperationEvent(requestVfCount1);
314         //
315         // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
316         //
317         requestAndCheckDecision(requestVfCount3, DENY);
318         //
319         // vfcount=6 above max of 5: should get a Deny
320         //
321         requestAndCheckDecision(requestVfCount6, DENY);
322     }
323
324     @Test
325     public void test5MissingFields() throws FileNotFoundException, IOException, XacmlApplicationException {
326         LOGGER.info("**************** Running test5 ****************");
327         //
328         // Most likely we would not get a policy with missing fields passed to
329         // us from the API. But in case that happens, or we decide that some fields
330         // will be optional due to re-working of how the XACML policies are built,
331         // let's add support in for that.
332         //
333         try (InputStream is = new FileInputStream("src/test/resources/guard.policy-minmax-missing-fields1.yaml")) {
334             //
335             // Have yaml parse it
336             //
337             Yaml yaml = new Yaml();
338             Map<String, Object> toscaObject = yaml.load(is);
339             //
340             // Load the policies
341             //
342             service.loadPolicies(toscaObject);
343             //
344             // We can create a DecisionRequest on the fly - no need
345             // to have it in the .json files
346             //
347             DecisionRequest request = new DecisionRequest();
348             request.setOnapName("JUnit");
349             request.setOnapComponent("test5MissingFields");
350             request.setRequestId(UUID.randomUUID().toString());
351             request.setAction("guard");
352             Map<String, Object> guard = new HashMap<>();
353             guard.put("actor", "FOO");
354             guard.put("recipe", "bar");
355             guard.put("vfCount", "4");
356             Map<String, Object> resource = new HashMap<>();
357             resource.put("guard", guard);
358             request.setResource(resource);
359             //
360             // Ask for a decision - should get permit
361             //
362             DecisionResponse response = service.makeDecision(request);
363             LOGGER.info("Looking for Permit Decision {}", response);
364             assertThat(response).isNotNull();
365             assertThat(response.getStatus()).isNotNull();
366             assertThat(response.getStatus()).isEqualTo("Permit");
367             //
368             // Try a deny
369             //
370             guard.put("vfCount", "10");
371             resource.put("guard", guard);
372             request.setResource(resource);
373             response = service.makeDecision(request);
374             LOGGER.info("Looking for Deny Decision {}", response);
375             assertThat(response).isNotNull();
376             assertThat(response.getStatus()).isNotNull();
377             assertThat(response.getStatus()).isEqualTo("Deny");
378         }
379     }
380
381     @SuppressWarnings("unchecked")
382     private void insertOperationEvent(DecisionRequest request) {
383         //
384         // Get the properties
385         //
386         Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
387         assertThat(properties).isNotNull();
388         //
389         // Add an entry
390         //
391         OnapOperationsHistoryDbao newEntry = new OnapOperationsHistoryDbao();
392         newEntry.setActor(properties.get("actor").toString());
393         newEntry.setOperation(properties.get("recipe").toString());
394         newEntry.setClName(properties.get("clname").toString());
395         newEntry.setOutcome("SUCCESS");
396         newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
397         newEntry.setEndtime(Date.from(Instant.now()));
398         newEntry.setRequestId(UUID.randomUUID().toString());
399         newEntry.setTarget(properties.get("target").toString());
400         em.getTransaction().begin();
401         em.persist(newEntry);
402         em.getTransaction().commit();
403     }
404
405     @AfterClass
406     public static void cleanup() throws Exception {
407         em.close();
408     }
409 }