b369ad311b0bfdcd4515a58377bd81c1de675167
[policy/xacml-pdp.git] / main / src / test / java / org / onap / policy / pdpx / main / rest / TestDecision.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
4  * Modifications Copyright (C) 2019 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
27 import com.google.gson.Gson;
28 import com.google.gson.GsonBuilder;
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 javax.ws.rs.client.Entity;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import javax.ws.rs.core.Response.Status;
44 import org.junit.AfterClass;
45 import org.junit.BeforeClass;
46 import org.junit.ClassRule;
47 import org.junit.Test;
48 import org.junit.rules.TemporaryFolder;
49 import org.onap.policy.common.endpoints.http.client.HttpClient;
50 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
51 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
52 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
53 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
54 import org.onap.policy.common.endpoints.parameters.TopicParameterGroup;
55 import org.onap.policy.common.utils.network.NetworkUtil;
56 import org.onap.policy.common.utils.resources.ResourceUtils;
57 import org.onap.policy.models.decisions.concepts.DecisionRequest;
58 import org.onap.policy.models.decisions.concepts.DecisionResponse;
59 import org.onap.policy.models.errors.concepts.ErrorResponse;
60 import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
61 import org.onap.policy.pdpx.main.parameters.CommonTestData;
62 import org.onap.policy.pdpx.main.parameters.XacmlApplicationParameters;
63 import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
64 import org.onap.policy.pdpx.main.startstop.Main;
65 import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 public class TestDecision {
70
71     private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
72
73     private static int port;
74     private static Main main;
75     private static HttpClient client;
76     private static CommonTestData testData = new CommonTestData();
77     private static final String APPLICATION_XACML_XML = "application/xacml+xml";
78     private static final String APPLICATION_XACML_JSON = "application/xacml+json";
79
80     @ClassRule
81     public static final TemporaryFolder appsFolder = new TemporaryFolder();
82
83     /**
84      * BeforeClass setup environment.
85      * @throws IOException Cannot create temp apps folder
86      * @throws Exception exception if service does not start
87      */
88     @BeforeClass
89     public static void beforeClass() throws Exception {
90         System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
91         System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
92
93         port = NetworkUtil.allocPort();
94
95         //
96         // Copy test directory over of the application directories
97         //
98         Path src = Paths.get("src/test/resources/apps");
99         File apps = appsFolder.newFolder("apps");
100         Files.walk(src).forEach(source -> {
101             copy(source, apps.toPath().resolve(src.relativize(source)));
102         });
103         //
104         // Get the parameters file correct.
105         //
106         RestServerParameters rest =
107             testData.toObject(testData.getRestServerParametersMap(port), RestServerParameters.class);
108         RestClientParameters policyApiParameters =
109                         testData.toObject(testData.getPolicyApiParametersMap(false), RestClientParameters.class);
110         TopicParameterGroup topicParameterGroup =
111                         testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
112         final XacmlApplicationParameters xacmlApplicationParameters =
113                 testData.toObject(testData.getXacmlapplicationParametersMap(false,
114                         apps.getAbsolutePath().toString()), XacmlApplicationParameters.class);
115         XacmlPdpParameterGroup params =
116                 new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", "xacml", rest, policyApiParameters,
117                         topicParameterGroup, xacmlApplicationParameters);
118         final Gson gson = new GsonBuilder().create();
119         File fileParams = appsFolder.newFile("params.json");
120         String jsonParams = gson.toJson(params);
121         LOGGER.info("Creating new params: {}", jsonParams);
122         Files.write(fileParams.toPath(), jsonParams.getBytes());
123         //
124         // Start the service
125         //
126         main = startXacmlPdpService(fileParams);
127         XacmlPdpActivator.getCurrent().enableApi();
128         //
129         // Make sure it is running
130         //
131         if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
132             throw new IllegalStateException("Cannot connect to port " + port);
133         }
134         //
135         // Create a client
136         //
137         client = getNoAuthHttpClient();
138     }
139
140     @AfterClass
141     public static void after() throws PolicyXacmlPdpException {
142         stopXacmlPdpService(main);
143         client.shutdown();
144     }
145
146     @Test
147     public void testDecision_UnsupportedAction() throws Exception {
148         LOGGER.info("Running test testDecision_UnsupportedAction");
149
150         DecisionRequest request = new DecisionRequest();
151         request.setOnapName("DROOLS");
152         request.setAction("foo");
153         Map<String, Object> guard = new HashMap<String, Object>();
154         guard.put("actor", "foo");
155         guard.put("recipe", "bar");
156         guard.put("target", "somevnf");
157         guard.put("clname", "phoneyloop");
158         request.setResource(guard);
159
160         ErrorResponse response = getErrorDecision(request);
161         LOGGER.info("Response {}", response);
162         assertThat(response.getResponseCode()).isEqualTo(Status.BAD_REQUEST);
163         assertThat(response.getErrorMessage()).isEqualToIgnoringCase("No application for action foo");
164     }
165
166     @Test
167     public void testDecision_Guard() throws KeyManagementException, NoSuchAlgorithmException,
168         ClassNotFoundException {
169         LOGGER.info("Running test testDecision_Guard");
170
171         DecisionRequest request = new DecisionRequest();
172         request.setOnapName("DROOLS");
173         request.setAction("guard");
174         Map<String, Object> guard = new HashMap<String, Object>();
175         guard.put("actor", "foo");
176         guard.put("recipe", "bar");
177         guard.put("target", "somevnf");
178         guard.put("clname", "phoneyloop");
179         request.setResource(guard);
180
181         DecisionResponse response = getDecision(request);
182         LOGGER.info("Response {}", response);
183         assertThat(response.getStatus()).isEqualTo("Permit");
184     }
185
186     @Test
187     public void testDecision_Native() throws IOException {
188         LOGGER.info("Running test testDecision_Native");
189
190         String xmlRequestAsString = ResourceUtils.getResourceAsString(
191                 "src/test/resources/decisions/decision.native.request.xml");
192         if (xmlRequestAsString == null) {
193             throw new IOException("failed to read the xml request");
194         }
195
196         String jsonRequestAsString = ResourceUtils.getResourceAsString(
197                 "src/test/resources/decisions/decision.native.request.json");
198         if (jsonRequestAsString == null) {
199             throw new IOException("failed to read the json request");
200         }
201
202         String responseFromXmlRequest = getNativeDecision(xmlRequestAsString, APPLICATION_XACML_XML);
203         LOGGER.info("Response from xml request {}", responseFromXmlRequest);
204         assertThat(responseFromXmlRequest).contains("<Response xmlns=").contains("NotApplicable");
205
206         String responseFromJsonRequest = getNativeDecision(jsonRequestAsString, APPLICATION_XACML_JSON);
207         LOGGER.info("Response from json request {}", responseFromJsonRequest);
208         assertThat(responseFromJsonRequest).contains("\"Response\":").contains("NotApplicable");
209     }
210
211     private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
212         final String[] XacmlPdpConfigParameters = {"-c", params.getAbsolutePath()};
213         return new Main(XacmlPdpConfigParameters);
214     }
215
216     private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
217         main.shutdown();
218     }
219
220     private DecisionResponse getDecision(DecisionRequest request) {
221         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
222         Response response = client.post("/decision", entityRequest, Collections.emptyMap());
223
224         assertEquals(200, response.getStatus());
225
226         return HttpClient.getBody(response, DecisionResponse.class);
227     }
228
229     private String getNativeDecision(String request, String mediaType) {
230         Entity<String> entityRequest = Entity.entity(request, mediaType);
231         Response response = client.post("/xacml", entityRequest, Map.of("Accept", mediaType));
232
233         assertEquals(200, response.getStatus());
234
235         return HttpClient.getBody(response, String.class);
236     }
237
238     private ErrorResponse getErrorDecision(DecisionRequest request) {
239         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
240         Response response = client.post("/decision", entityRequest, Collections.emptyMap());
241
242         assertEquals(400, response.getStatus());
243
244         return HttpClient.getBody(response, ErrorResponse.class);
245     }
246
247     private static HttpClient getNoAuthHttpClient() throws HttpClientConfigException {
248         return HttpClientFactoryInstance.getClientFactory().build(RestClientParameters.builder()
249                 .clientName("testDecisionClient")
250                 .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(port)
251                 .basePath("policy/pdpx/v1")
252                 .userName("healthcheck").password("zb!XztG34").managed(true).build());
253     }
254
255     private static void copy(Path source, Path dest) {
256         try {
257             LOGGER.info("Copying {} to {}", source, dest);
258             Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
259         } catch (IOException e) {
260             LOGGER.error("Failed to copy {} to {}", source, dest);
261         }
262     }
263 }