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