3e525e91c72969eb533815a379210b35c2bccecf
[policy/xacml-pdp.git] / main / src / test / java / org / onap / policy / pdpx / main / rest / TestAbbreviateDecisionResults.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
4  * Modifications Copyright (C) 2020 Nordix Foundation
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pdpx.main.rest;
23
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertTrue;
28
29 import java.io.File;
30 import java.io.IOException;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.nio.file.StandardCopyOption;
35 import java.security.KeyManagementException;
36 import java.security.NoSuchAlgorithmException;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.Map;
40 import java.util.Properties;
41 import java.util.ServiceLoader;
42 import javax.ws.rs.client.Entity;
43 import javax.ws.rs.core.MediaType;
44 import javax.ws.rs.core.Response;
45 import org.junit.AfterClass;
46 import org.junit.BeforeClass;
47 import org.junit.ClassRule;
48 import org.junit.Test;
49 import org.junit.rules.TemporaryFolder;
50 import org.onap.policy.common.endpoints.http.client.HttpClient;
51 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
52 import org.onap.policy.common.endpoints.http.client.internal.JerseyClient;
53 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
54 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
55 import org.onap.policy.common.endpoints.parameters.TopicParameterGroup;
56 import org.onap.policy.common.utils.coder.CoderException;
57 import org.onap.policy.common.utils.coder.StandardCoder;
58 import org.onap.policy.common.utils.network.NetworkUtil;
59 import org.onap.policy.models.decisions.concepts.DecisionRequest;
60 import org.onap.policy.models.decisions.concepts.DecisionResponse;
61 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
62 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
63 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
64 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
65 import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
66 import org.onap.policy.pdpx.main.parameters.CommonTestData;
67 import org.onap.policy.pdpx.main.parameters.XacmlApplicationParameters;
68 import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
69 import org.onap.policy.pdpx.main.startstop.Main;
70 import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
71 import org.onap.policy.xacml.pdp.application.monitoring.MonitoringPdpApplication;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 public class TestAbbreviateDecisionResults {
76
77     private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
78
79     private static int port;
80     private static Main main;
81     private static HttpClient client;
82     private static CommonTestData testData = new CommonTestData();
83
84     private static Properties properties = new Properties();
85     private static File propertiesFile;
86     private static XacmlApplicationServiceProvider service;
87
88     private static RestClientParameters policyApiParameters;
89
90     @ClassRule
91     public static final TemporaryFolder appsFolder = new TemporaryFolder();
92
93     /**
94      * BeforeClass setup environment.
95      *
96      * @throws IOException Cannot create temp apps folder
97      * @throws Exception   exception if service does not start
98      */
99     @BeforeClass
100     public static void beforeClass() throws Exception {
101         port = NetworkUtil.allocPort();
102         //
103         // Copy test directory over of the application directories
104         //
105         Path src = Paths.get("src/test/resources/apps");
106         File apps = appsFolder.newFolder("apps");
107         Files.walk(src).forEach(source -> {
108             copy(source, apps.toPath().resolve(src.relativize(source)));
109         });
110
111         // Start the Monitoring Application
112         startXacmlApplicationService(apps);
113
114         // Load monitoring policy
115         TestUtils.loadPolicies("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml", service);
116
117         // Create parameters for XacmlPdPService
118         RestServerParameters rest = testData.toObject(testData.getRestServerParametersMap(port),
119                 RestServerParameters.class);
120         policyApiParameters = testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
121         TopicParameterGroup topicParameterGroup = testData.toObject(testData.getTopicParametersMap(false),
122                 TopicParameterGroup.class);
123         final XacmlApplicationParameters xacmlApplicationParameters =
124                 testData.toObject(testData.getXacmlapplicationParametersMap(false,
125                         apps.getAbsolutePath().toString()), XacmlApplicationParameters.class);
126         XacmlPdpParameterGroup params =
127                 new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters,
128                 topicParameterGroup, xacmlApplicationParameters);
129         StandardCoder gson = new StandardCoder();
130         File fileParams = appsFolder.newFile("params.json");
131         String jsonParams = gson.encode(params);
132         LOGGER.info("Creating new params: {}", jsonParams);
133         Files.write(fileParams.toPath(), jsonParams.getBytes());
134         //
135         // Start the service
136         //
137         main = startXacmlPdpService(fileParams);
138         XacmlPdpActivator.getCurrent().enableApi();
139         //
140         // Make sure it is running
141         //
142         if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
143             throw new IllegalStateException("Cannot connect to port " + port);
144         }
145         //
146         // Create a client
147         //
148         client = getNoAuthHttpClient();
149     }
150
151     /**
152      * Clean up.
153      */
154     @AfterClass
155     public static void after() throws PolicyXacmlPdpException {
156         stopXacmlPdpService(main);
157         client.shutdown();
158     }
159
160     /**
161      * Tests if the Decision Response contains abbreviated results. Specifically, "properties", "name" and "version"
162      * should have been removed from the response.
163      */
164     @Test
165     public void testAbbreviateDecisionResult() throws HttpClientConfigException {
166
167         LOGGER.info("Running testAbbreviateDecisionResult");
168
169         // Create DecisionRequest
170         DecisionRequest request = new DecisionRequest();
171         request.setOnapName("DCAE");
172         request.setOnapComponent("PolicyHandler");
173         request.setOnapInstance("622431a4-9dea-4eae-b443-3b2164639c64");
174         request.setAction("configure");
175         Map<String, Object> resource = new HashMap<String, Object>();
176         resource.put("policy-id", "onap.scaleout.tca");
177         request.setResource(resource);
178
179         // Query decision API
180         DecisionResponse response = getDecision(request);
181         LOGGER.info("Decision Response {}", response);
182
183         assertFalse(response.getPolicies().isEmpty());
184
185         @SuppressWarnings("unchecked")
186         Map<String, Object> policy = (Map<String, Object>) response.getPolicies().get("onap.scaleout.tca");
187         assertTrue(policy.containsKey("type"));
188         assertFalse(policy.containsKey("properties"));
189         assertFalse(policy.containsKey("name"));
190         assertFalse(policy.containsKey("version"));
191         assertTrue(policy.containsKey("metadata"));
192     }
193
194     private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
195         final String[] XacmlPdpConfigParameters = { "-c", params.getAbsolutePath() };
196         return new Main(XacmlPdpConfigParameters);
197     }
198
199     private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
200         main.shutdown();
201     }
202
203     /**
204      * Performs the POST request to Decision API.
205      *
206      */
207     private DecisionResponse getDecision(DecisionRequest request) throws HttpClientConfigException {
208
209         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
210         Response response = client.post("", entityRequest, Collections.emptyMap());
211
212         assertEquals(200, response.getStatus());
213         return HttpClient.getBody(response, DecisionResponse.class);
214     }
215
216     /**
217      * Create HttpClient.
218      *
219      */
220     private static HttpClient getNoAuthHttpClient()
221             throws HttpClientConfigException, KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
222         RestClientParameters clientParams = new RestClientParameters();
223         clientParams.setClientName("testName");
224         clientParams.setUseHttps(false);
225         clientParams.setAllowSelfSignedCerts(false);
226         clientParams.setHostname("localhost");
227         clientParams.setPort(port);
228         clientParams.setBasePath("policy/pdpx/v1/decision?abbrev=true");
229         clientParams.setUserName("healthcheck");
230         clientParams.setPassword("zb!XztG34");
231         clientParams.setManaged(true);
232         client = new JerseyClient(clientParams);
233         return client;
234     }
235
236     private static void copy(Path source, Path dest) {
237         try {
238             LOGGER.info("Copying {} to {}", source, dest);
239             Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
240         } catch (IOException e) {
241             LOGGER.error("Failed to copy {} to {}", source, dest);
242         }
243     }
244
245     /**
246      * Initializes the Monitoring application service.
247      *
248      * @param apps - the path to xacml.properties file
249      */
250     private static void startXacmlApplicationService(File apps)
251             throws XacmlApplicationException, CoderException, IOException {
252         LOGGER.info("****** Starting Xacml Application Service ******");
253         //
254         // Setup our temporary folder
255         //
256         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> {
257             new File(apps, "monitoring/" + filename).delete();
258             return appsFolder.newFile("apps/monitoring/" + filename);
259         };
260         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
261                 "../applications/monitoring/src/test/resources/xacml.properties", properties, myCreator);
262         //
263         // Load XacmlApplicationServiceProvider service
264         //
265         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader = ServiceLoader
266                 .load(XacmlApplicationServiceProvider.class);
267         //
268         // Look for our class instance and save it
269         //
270         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
271         for (XacmlApplicationServiceProvider application : applicationLoader) {
272             //
273             // Is it our service?
274             //
275             if (application instanceof MonitoringPdpApplication) {
276                 //
277                 // Should be the first and only one
278                 //
279                 assertThat(service).isNull();
280                 service = application;
281             }
282             strDump.append(application.applicationName());
283             strDump.append(" supports ");
284             strDump.append(application.supportedPolicyTypes());
285             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
286         }
287         LOGGER.debug("{}", strDump);
288         //
289         // Tell it to initialize based on the properties file
290         // we just built for it.
291         //
292         service.initialize(propertiesFile.toPath().getParent(), null);
293     }
294 }