2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2020 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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pdpx.main.rest;
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.junit.Assert.assertEquals;
27 import com.google.gson.Gson;
28 import com.google.gson.GsonBuilder;
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;
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.event.comm.bus.internal.BusTopicParams;
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.HttpClientFactoryInstance;
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.XacmlPdpParameterGroup;
63 import org.onap.policy.pdpx.main.startstop.Main;
64 import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 public class TestDecision {
70 private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
72 private static int port;
73 private static Main main;
74 private static HttpClient client;
75 private static CommonTestData testData = new CommonTestData();
76 private static final String APPLICATION_XACML_XML = "application/xacml+xml";
77 private static final String APPLICATION_XACML_JSON = "application/xacml+json";
80 public static final TemporaryFolder appsFolder = new TemporaryFolder();
83 * BeforeClass setup environment.
84 * @throws IOException Cannot create temp apps folder
85 * @throws Exception exception if service does not start
88 public static void beforeClass() throws Exception {
89 System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
90 System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
92 port = NetworkUtil.allocPort();
95 // Copy test directory over of the application directories
97 Path src = Paths.get("src/test/resources/apps");
98 File apps = appsFolder.newFolder("apps");
99 Files.walk(src).forEach(source -> {
100 copy(source, apps.toPath().resolve(src.relativize(source)));
103 // Get the parameters file correct.
105 RestServerParameters rest =
106 testData.toObject(testData.getRestServerParametersMap(port), RestServerParameters.class);
107 RestServerParameters policyApiParameters =
108 testData.toObject(testData.getPolicyApiParametersMap(false), RestServerParameters.class);
109 TopicParameterGroup topicParameterGroup =
110 testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
111 XacmlPdpParameterGroup params =
112 new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", rest, policyApiParameters,
113 topicParameterGroup, apps.getAbsolutePath());
114 final Gson gson = new GsonBuilder().create();
115 File fileParams = appsFolder.newFile("params.json");
116 String jsonParams = gson.toJson(params);
117 LOGGER.info("Creating new params: {}", jsonParams);
118 Files.write(fileParams.toPath(), jsonParams.getBytes());
122 main = startXacmlPdpService(fileParams);
123 XacmlPdpActivator.getCurrent().startXacmlRestController();
125 // Make sure it is running
127 if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
128 throw new IllegalStateException("Cannot connect to port " + port);
133 client = getNoAuthHttpClient();
137 public static void after() throws PolicyXacmlPdpException {
138 stopXacmlPdpService(main);
143 public void testDecision_UnsupportedAction() throws Exception {
144 LOGGER.info("Running test testDecision_UnsupportedAction");
146 DecisionRequest request = new DecisionRequest();
147 request.setOnapName("DROOLS");
148 request.setAction("foo");
149 Map<String, Object> guard = new HashMap<String, Object>();
150 guard.put("actor", "foo");
151 guard.put("recipe", "bar");
152 guard.put("target", "somevnf");
153 guard.put("clname", "phoneyloop");
154 request.setResource(guard);
156 ErrorResponse response = getErrorDecision(request);
157 LOGGER.info("Response {}", response);
158 assertThat(response.getResponseCode()).isEqualTo(Status.BAD_REQUEST);
159 assertThat(response.getErrorMessage()).isEqualToIgnoringCase("No application for action foo");
163 public void testDecision_Guard() throws KeyManagementException, NoSuchAlgorithmException,
164 ClassNotFoundException {
165 LOGGER.info("Running test testDecision_Guard");
167 DecisionRequest request = new DecisionRequest();
168 request.setOnapName("DROOLS");
169 request.setAction("guard");
170 Map<String, Object> guard = new HashMap<String, Object>();
171 guard.put("actor", "foo");
172 guard.put("recipe", "bar");
173 guard.put("target", "somevnf");
174 guard.put("clname", "phoneyloop");
175 request.setResource(guard);
177 DecisionResponse response = getDecision(request);
178 LOGGER.info("Response {}", response);
179 assertThat(response.getStatus()).isEqualTo("Permit");
183 public void testDecision_Native() throws IOException {
184 LOGGER.info("Running test testDecision_Native");
186 String xmlRequestAsString = ResourceUtils.getResourceAsString(
187 "src/test/resources/decisions/decision.native.request.xml");
188 if (xmlRequestAsString == null) {
189 throw new IOException("failed to read the xml request");
192 String jsonRequestAsString = ResourceUtils.getResourceAsString(
193 "src/test/resources/decisions/decision.native.request.json");
194 if (jsonRequestAsString == null) {
195 throw new IOException("failed to read the json request");
198 String responseFromXmlRequest = getNativeDecision(xmlRequestAsString, APPLICATION_XACML_XML);
199 LOGGER.info("Response from xml request {}", responseFromXmlRequest);
200 assertThat(responseFromXmlRequest).contains("NOTAPPLICABLE");
202 String responseFromJsonRequest = getNativeDecision(jsonRequestAsString, APPLICATION_XACML_JSON);
203 LOGGER.info("Response from json request {}", responseFromJsonRequest);
204 assertThat(responseFromJsonRequest).contains("NOTAPPLICABLE");
207 private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
208 final String[] XacmlPdpConfigParameters = {"-c", params.getAbsolutePath()};
209 return new Main(XacmlPdpConfigParameters);
212 private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
216 private DecisionResponse getDecision(DecisionRequest request) {
217 Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
218 Response response = client.post("/decision", entityRequest, Collections.emptyMap());
220 assertEquals(200, response.getStatus());
222 return HttpClient.getBody(response, DecisionResponse.class);
225 private String getNativeDecision(String request, String mediaType) {
226 Entity<String> entityRequest = Entity.entity(request, mediaType);
227 Response response = client.post("/xacml", entityRequest, Collections.emptyMap());
229 assertEquals(200, response.getStatus());
231 return HttpClient.getBody(response, String.class);
234 private ErrorResponse getErrorDecision(DecisionRequest request) {
235 Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
236 Response response = client.post("/decision", entityRequest, Collections.emptyMap());
238 assertEquals(400, response.getStatus());
240 return HttpClient.getBody(response, ErrorResponse.class);
243 private static HttpClient getNoAuthHttpClient() throws HttpClientConfigException {
244 return HttpClientFactoryInstance.getClientFactory().build(BusTopicParams.builder()
245 .clientName("testDecisionClient")
246 .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(port)
247 .basePath("policy/pdpx/v1")
248 .userName("healthcheck").password("zb!XztG34").managed(true).build());
251 private static void copy(Path source, Path dest) {
253 LOGGER.info("Copying {} to {}", source, dest);
254 Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
255 } catch (IOException e) {
256 LOGGER.error("Failed to copy {} to {}", source, dest);