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