Adding optimization application finish guard
[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.util.HashMap;
33 import java.util.Iterator;
34 import java.util.Map;
35 import java.util.Properties;
36 import java.util.ServiceLoader;
37 import java.util.UUID;
38
39 import org.junit.BeforeClass;
40 import org.junit.ClassRule;
41 import org.junit.FixMethodOrder;
42 import org.junit.Test;
43 import org.junit.rules.TemporaryFolder;
44 import org.junit.runners.MethodSorters;
45 import org.onap.policy.common.utils.coder.CoderException;
46 import org.onap.policy.common.utils.coder.StandardCoder;
47 import org.onap.policy.common.utils.resources.TextFileUtils;
48 import org.onap.policy.models.decisions.concepts.DecisionRequest;
49 import org.onap.policy.models.decisions.concepts.DecisionResponse;
50 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
51 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.yaml.snakeyaml.Yaml;
55
56 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
57 public class GuardPdpApplicationTest {
58
59     private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
60     private static Properties properties = new Properties();
61     private static File propertiesFile;
62     private static XacmlApplicationServiceProvider service;
63     private static DecisionRequest requestGuardPermit;
64     private static DecisionRequest requestGuardDeny;
65     private static DecisionRequest requestGuardDeny2;
66     private static StandardCoder gson = new StandardCoder();
67
68     @ClassRule
69     public static final TemporaryFolder policyFolder = new TemporaryFolder();
70
71     /**
72      * Copies the xacml.properties and policies files into
73      * temporary folder and loads the service provider saving
74      * instance of provider off for other tests to use.
75      */
76     @BeforeClass
77     public static void setUp() throws Exception {
78         //
79         // Setup our temporary folder
80         //
81         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
82         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
83                 properties, myCreator);
84         //
85         // Load service
86         //
87         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
88                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
89         //
90         // Find the guard service application and save for use in all the tests
91         //
92         StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
93         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
94         while (iterator.hasNext()) {
95             XacmlApplicationServiceProvider application = iterator.next();
96             //
97             // Is it our service?
98             //
99             if (application instanceof GuardPdpApplication) {
100                 //
101                 // Should be the first and only one
102                 //
103                 assertThat(service).isNull();
104                 service = application;
105             }
106             strDump.append(application.applicationName());
107             strDump.append(" supports ");
108             strDump.append(application.supportedPolicyTypes());
109             strDump.append(System.lineSeparator());
110         }
111         LOGGER.debug("{}", strDump);
112         //
113         // Tell it to initialize based on the properties file
114         // we just built for it.
115         //
116         service.initialize(propertiesFile.toPath().getParent());
117     }
118
119     @Test
120     public void test1Basics() throws CoderException, IOException {
121         //
122         // Load Single Decision Request
123         //
124         requestGuardPermit = gson.decode(
125                 TextFileUtils.getTextFileAsString(
126                     "../../main/src/test/resources/decisions/decision.guard.shouldpermit.input.json"),
127                     DecisionRequest.class);
128         //
129         // Load Single Decision Request
130         //
131         requestGuardDeny = gson.decode(TextFileUtils.getTextFileAsString(
132                 "../../main/src/test/resources/decisions/decision.guard.shoulddeny.input.json"),
133                 DecisionRequest.class);
134         //
135         // Load Single Decision Request
136         //
137         requestGuardDeny2 = gson.decode(TextFileUtils.getTextFileAsString(
138                 "../../main/src/test/resources/decisions/decision.guard.shoulddeny.input2.json"),
139                 DecisionRequest.class);
140         //
141         // Make sure there's an application name
142         //
143         assertThat(service.applicationName()).isNotEmpty();
144         //
145         // Decisions
146         //
147         assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
148         assertThat(service.actionDecisionsSupported()).contains("guard");
149         //
150         // Ensure it has the supported policy types and
151         // can support the correct policy types.
152         //
153         assertThat(service.supportedPolicyTypes()).isNotEmpty();
154         assertThat(service.supportedPolicyTypes().size()).isEqualTo(2);
155         assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))
156             .isTrue();
157         assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))
158             .isFalse();
159         assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.MinMax", "1.0.0")).isTrue();
160         assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.MinMax", "1.0.1")).isFalse();
161         assertThat(service.canSupportPolicyType("onap.foo", "1.0.1")).isFalse();
162     }
163
164     @Test
165     public void test2NoPolicies() {
166         //
167         // Ask for a decision
168         //
169         DecisionResponse response = service.makeDecision(requestGuardPermit);
170         LOGGER.info("Decision {}", response);
171
172         assertThat(response).isNotNull();
173         assertThat(response.getStatus()).isEqualTo("Permit");
174     }
175
176     @Test
177     public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException {
178         //
179         // Now load the vDNS frequency limiter Policy - make sure
180         // the pdp can support it and have it load
181         // into the PDP.
182         //
183         try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml")) {
184             //
185             // Have yaml parse it
186             //
187             Yaml yaml = new Yaml();
188             Map<String, Object> toscaObject = yaml.load(is);
189             //
190             // Load the policies
191             //
192             service.loadPolicies(toscaObject);
193             //
194             // Ask for a decision - should get permit
195             //
196             DecisionResponse response = service.makeDecision(requestGuardPermit);
197             LOGGER.info("Looking for Permit Decision {}", response);
198
199             assertThat(response).isNotNull();
200             assertThat(response.getStatus()).isNotNull();
201             assertThat(response.getStatus()).isEqualTo("Permit");
202             //
203             // Dump it out as Json
204             //
205             LOGGER.info(gson.encode(response));
206             //
207             // Ask for a decision - should get deny
208             //
209             response = service.makeDecision(requestGuardDeny2);
210             LOGGER.info("Looking for Deny Decision {}", response);
211             assertThat(response).isNotNull();
212             assertThat(response.getStatus()).isNotNull();
213             assertThat(response.getStatus()).isEqualTo("Deny");
214             //
215             // Dump it out as Json
216             //
217             LOGGER.info(gson.encode(response));
218         }
219     }
220
221     @Test
222     public void test4MinMax() throws CoderException, FileNotFoundException, IOException {
223         //
224         // Now load the vDNS min max Policy - make sure
225         // the pdp can support it and have it load
226         // into the PDP.
227         //
228         try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml")) {
229             //
230             // Have yaml parse it
231             //
232             Yaml yaml = new Yaml();
233             Map<String, Object> toscaObject = yaml.load(is);
234             //
235             // Load the policies
236             //
237             service.loadPolicies(toscaObject);
238             //
239             // Ask for a decision - should get permit
240             //
241             DecisionResponse response = service.makeDecision(requestGuardPermit);
242             LOGGER.info("Looking for Permit Decision {}", response);
243
244             assertThat(response).isNotNull();
245             assertThat(response.getStatus()).isNotNull();
246             assertThat(response.getStatus()).isEqualTo("Permit");
247             //
248             // Dump it out as Json
249             //
250             LOGGER.info(gson.encode(response));
251             //
252             // Ask for a decision - should get deny
253             //
254             response = service.makeDecision(requestGuardDeny);
255             LOGGER.info("Looking for Deny Decision {}", response);
256             assertThat(response).isNotNull();
257             assertThat(response.getStatus()).isNotNull();
258             assertThat(response.getStatus()).isEqualTo("Deny");
259             //
260             // Dump it out as Json
261             //
262             LOGGER.info(gson.encode(response));
263         }
264     }
265
266     @Test
267     public void test5MissingFields() throws FileNotFoundException, IOException {
268         LOGGER.debug("Running test5");
269         //
270         // Most likely we would not get a policy with missing fields passed to
271         // us from the API. But in case that happens, or we decide that some fields
272         // will be optional due to re-working of how the XACML policies are built,
273         // let's add support in for that.
274         //
275         try (InputStream is = new FileInputStream("src/test/resources/guard.policy-minmax-missing-fields1.yaml")) {
276             //
277             // Have yaml parse it
278             //
279             Yaml yaml = new Yaml();
280             Map<String, Object> toscaObject = yaml.load(is);
281             //
282             // Load the policies
283             //
284             service.loadPolicies(toscaObject);
285             //
286             // We can create a DecisionRequest on the fly - no need
287             // to have it in the .json files
288             //
289             DecisionRequest request = new DecisionRequest();
290             request.setOnapName("JUnit");
291             request.setOnapComponent("test5MissingFields");
292             request.setRequestId(UUID.randomUUID().toString());
293             request.setAction("guard");
294             Map<String, Object> guard = new HashMap<>();
295             guard.put("actor", "FOO");
296             guard.put("recipe", "bar");
297             guard.put("vfCount", "4");
298             Map<String, Object> resource = new HashMap<>();
299             resource.put("guard", guard);
300             request.setResource(resource);
301             //
302             // Ask for a decision - should get permit
303             //
304             DecisionResponse response = service.makeDecision(request);
305             LOGGER.info("Looking for Permit Decision {}", response);
306             assertThat(response).isNotNull();
307             assertThat(response.getStatus()).isNotNull();
308             assertThat(response.getStatus()).isEqualTo("Permit");
309             //
310             // Try a deny
311             //
312             guard.put("vfCount", "10");
313             resource.put("guard", guard);
314             request.setResource(resource);
315             response = service.makeDecision(request);
316             LOGGER.info("Looking for Deny Decision {}", response);
317             assertThat(response).isNotNull();
318             assertThat(response.getStatus()).isNotNull();
319             assertThat(response.getStatus()).isEqualTo("Deny");
320         }
321     }
322 }