7fab09b2e24038e6db24f32bc9e5648dd56d6f1f
[policy/xacml-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2021 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.xacml.pdp.application.monitoring;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27
28 import com.att.research.xacml.api.Response;
29 import java.io.File;
30 import java.io.IOException;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Properties;
36 import java.util.ServiceLoader;
37 import org.apache.commons.lang3.tuple.Pair;
38 import org.junit.BeforeClass;
39 import org.junit.ClassRule;
40 import org.junit.FixMethodOrder;
41 import org.junit.Test;
42 import org.junit.rules.TemporaryFolder;
43 import org.junit.runners.MethodSorters;
44 import org.onap.policy.common.utils.coder.CoderException;
45 import org.onap.policy.common.utils.coder.StandardCoder;
46 import org.onap.policy.common.utils.resources.TextFileUtils;
47 import org.onap.policy.models.decisions.concepts.DecisionRequest;
48 import org.onap.policy.models.decisions.concepts.DecisionResponse;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
51 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
52 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
53 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
54 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
59 public class MonitoringPdpApplicationTest {
60
61     private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplicationTest.class);
62     private static Properties properties = new Properties();
63     private static File propertiesFile;
64     private static XacmlApplicationServiceProvider service;
65     private static DecisionRequest requestSinglePolicy;
66     private static DecisionRequest requestPolicyType;
67
68     private static StandardCoder gson = new StandardCoder();
69
70     @ClassRule
71     public static final TemporaryFolder policyFolder = new TemporaryFolder();
72
73     /**
74      * Copies the xacml.properties and policies files into
75      * temporary folder and loads the service provider saving
76      * instance of provider off for other tests to use.
77      */
78     @BeforeClass
79     public static void setup() throws Exception {
80         //
81         // Load Single Decision Request
82         //
83         requestSinglePolicy = gson.decode(
84                 TextFileUtils
85                     .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
86                     DecisionRequest.class);
87         // Load Single Decision Request
88         //
89         requestPolicyType = gson.decode(
90                 TextFileUtils
91                 .getTextFileAsString("../../main/src/test/resources/decisions/decision.policytype.input.json"),
92                 DecisionRequest.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 XacmlApplicationServiceProvider service
101         //
102         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
103                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
104         //
105         // Look for our class instance and save it
106         //
107         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
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 MonitoringPdpApplication) {
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(XacmlPolicyUtils.LINE_SEPARATOR);
125         }
126         LOGGER.debug("{}", 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(), null);
132     }
133
134     @Test
135     public void test1Basics() {
136         //
137         // Make sure there's an application name
138         //
139         assertThat(service.applicationName()).isNotEmpty();
140         //
141         // Ensure it has the supported policy types and
142         // can support the correct policy types.
143         //
144         assertThat(service.canSupportPolicyType(
145                 new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "1.0.0"))).isTrue();
146         assertThat(service.canSupportPolicyType(
147                 new ToscaConceptIdentifier(
148                 "onap.policies.monitoring.foobar", "1.0.1"))).isTrue();
149         assertThat(service.canSupportPolicyType(
150                 new ToscaConceptIdentifier("onap.foobar", "1.0.0"))).isFalse();
151         //
152         // Ensure it supports decisions
153         //
154         assertThat(service.actionDecisionsSupported()).contains("configure");
155     }
156
157     @Test
158     public void test2NoPolicies() {
159         //
160         // Ask for a decision
161         //
162         Pair<DecisionResponse, Response> decision = service.makeDecision(requestSinglePolicy, null);
163         LOGGER.info("Decision {}", decision);
164
165         assertThat(decision.getKey()).isNotNull();
166         assertThat(decision.getKey().getPolicies()).isEmpty();
167         //
168         // Test the branch for query params, and we have no policy anyway
169         //
170         Map<String, String[]> requestQueryParams = new HashMap<>();
171         decision = service.makeDecision(requestSinglePolicy, requestQueryParams);
172         LOGGER.info("Decision {}", decision);
173
174         assertThat(decision.getKey()).isNotNull();
175         assertThat(decision.getKey().getPolicies()).isEmpty();
176         //
177         // Test the branch for query params, and we have no policy anyway
178         //
179         requestQueryParams.put("abbrev", new String[] {"false"});
180         decision = service.makeDecision(requestSinglePolicy, requestQueryParams);
181         LOGGER.info("Decision {}", decision);
182
183         assertThat(decision.getKey()).isNotNull();
184         assertThat(decision.getKey().getPolicies()).isEmpty();
185         //
186         // Monitoring applications should not have this information returned
187         //
188         assertThat(decision.getKey().getAdvice()).isNull();
189         assertThat(decision.getKey().getObligations()).isNull();
190         assertThat(decision.getKey().getAttributes()).isNull();
191     }
192
193     @SuppressWarnings("unchecked")
194     @Test
195     public void test3AddvDnsPolicy() throws IOException, CoderException, XacmlApplicationException {
196         //
197         // Now load the vDNS Policy - make sure
198         // the pdp can support it and have it load
199         // into the PDP.
200         //
201         //
202         // Now load the monitoring policies
203         //
204         final List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies("src/test/resources/vDNS.policy.input.yaml",
205                 service);
206         //
207         // Ask for a decision
208         //
209         Pair<DecisionResponse, Response> decision = service.makeDecision(requestSinglePolicy, null);
210         LOGGER.info("Decision {}", decision);
211         //
212         // Should have one policy returned
213         //
214         assertThat(decision.getKey()).isNotNull();
215         assertThat(decision.getKey().getPolicies()).hasSize(1);
216         //
217         // Monitoring applications should not have this information returned
218         //
219         assertThat(decision.getKey().getAdvice()).isNull();
220         assertThat(decision.getKey().getObligations()).isNull();
221         assertThat(decision.getKey().getAttributes()).isNull();
222         //
223         // Dump it out as Json
224         //
225         LOGGER.info(gson.encode(decision.getKey()));
226         //
227         // Ask for a decision based on policy-type
228         //
229         decision = service.makeDecision(requestPolicyType, null);
230         LOGGER.info("Decision {}", decision);
231         //
232         // Should have one policy returned
233         //
234         assertThat(decision.getKey()).isNotNull();
235         assertThat(decision.getKey().getPolicies()).hasSize(1);
236         //
237         // Monitoring applications should not have this information returned
238         //
239         assertThat(decision.getKey().getAdvice()).isNull();
240         assertThat(decision.getKey().getObligations()).isNull();
241         assertThat(decision.getKey().getAttributes()).isNull();
242         //
243         // Validate the full policy is returned
244         //
245         Map<String, Object> jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get("onap.scaleout.tca");
246         assertThat(jsonPolicy).isNotNull();
247         assertThat(jsonPolicy.get("properties")).isNotNull();
248         //
249         // Dump it out as Json
250         //
251         LOGGER.info(gson.encode(decision.getKey()));
252         //
253         // Ask for abbreviated results
254         //
255         Map<String, String[]> requestQueryParams = new HashMap<>();
256         requestQueryParams.put("abbrev", new String[] {"true"});
257         decision = service.makeDecision(requestPolicyType, requestQueryParams);
258         LOGGER.info("Decision {}", decision);
259         //
260         // Should have one policy returned
261         //
262         assertThat(decision.getKey()).isNotNull();
263         assertThat(decision.getKey().getPolicies()).hasSize(1);
264         //
265         // Monitoring applications should not have this information returned
266         //
267         assertThat(decision.getKey().getAdvice()).isNull();
268         assertThat(decision.getKey().getObligations()).isNull();
269         assertThat(decision.getKey().getAttributes()).isNull();
270         //
271         // Validate an abbreviated policy is returned
272         //
273         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get("onap.scaleout.tca");
274         assertThat(jsonPolicy).isNotNull().doesNotContainKey("properties");
275         //
276         // Don't Ask for abbreviated results
277         //
278         requestQueryParams = new HashMap<>();
279         requestQueryParams.put("abbrev", new String[] {"false"});
280         decision = service.makeDecision(requestPolicyType, requestQueryParams);
281         LOGGER.info("Decision {}", decision);
282         //
283         // Should have one policy returned
284         //
285         assertThat(decision.getKey()).isNotNull();
286         assertThat(decision.getKey().getPolicies()).hasSize(1);
287         //
288         // Monitoring applications should not have this information returned
289         //
290         assertThat(decision.getKey().getAdvice()).isNull();
291         assertThat(decision.getKey().getObligations()).isNull();
292         assertThat(decision.getKey().getAttributes()).isNull();
293         //
294         // And should have full policy returned
295         //
296         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get("onap.scaleout.tca");
297         assertThat(jsonPolicy).isNotNull();
298         assertThat(jsonPolicy.get("properties")).isNotNull();
299         //
300         // Throw an unknown exception
301         //
302         requestQueryParams = new HashMap<>();
303         requestQueryParams.put("unknown", new String[] {"true"});
304         decision = service.makeDecision(requestPolicyType, requestQueryParams);
305         LOGGER.info("Decision {}", decision);
306
307         assertThat(decision.getKey()).isNotNull();
308         assertThat(decision.getKey().getPolicies()).hasSize(1);
309         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get("onap.scaleout.tca");
310         assertThat(jsonPolicy).isNotNull();
311         assertThat(jsonPolicy.get("properties")).isNotNull();
312         //
313         // Dump it out as Json
314         //
315         LOGGER.info(gson.encode(decision.getKey()));
316         //
317         // Now unload it
318         //
319         LOGGER.info("Now testing unloading of policy");
320         for (ToscaPolicy policy : loadedPolicies) {
321             assertThat(service.unloadPolicy(policy)).isTrue();
322         }
323         //
324         // Ask for a decision
325         //
326         decision = service.makeDecision(requestSinglePolicy, null);
327         LOGGER.info("Decision {}", decision.getKey());
328
329         assertThat(decision.getKey()).isNotNull();
330         assertThat(decision.getKey().getPolicies()).isEmpty();
331     }
332
333 }