e3ad7b675596f3fe976f8beb2c5988f312061a4b
[policy/xacml-pdp.git] / main / src / test / java / org / onap / policy / pdpx / main / rest / TestDecision.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 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.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.gson.GsonMessageBodyHandler;
56 import org.onap.policy.common.utils.network.NetworkUtil;
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;
67
68 public class TestDecision {
69
70     private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
71
72     private static int port;
73     private static Main main;
74     private static HttpClient client;
75     private static CommonTestData testData = new CommonTestData();
76
77     @ClassRule
78     public static final TemporaryFolder appsFolder = new TemporaryFolder();
79
80     /**
81      * BeforeClass setup environment.
82      * @throws IOException Cannot create temp apps folder
83      * @throws Exception exception if service does not start
84      */
85     @BeforeClass
86     public static void beforeClass() throws Exception {
87         System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
88         System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
89
90         port = NetworkUtil.allocPort();
91
92         //
93         // Copy test directory over of the application directories
94         //
95         Path src = Paths.get("src/test/resources/apps");
96         File apps = appsFolder.newFolder("apps");
97         Files.walk(src).forEach(source -> {
98             copy(source, apps.toPath().resolve(src.relativize(source)));
99         });
100         //
101         // Get the parameters file correct.
102         //
103         RestServerParameters rest =
104             testData.toObject(testData.getRestServerParametersMap(port), RestServerParameters.class);
105         RestServerParameters policyApiParameters =
106                         testData.toObject(testData.getPolicyApiParametersMap(false), RestServerParameters.class);
107         TopicParameterGroup topicParameterGroup =
108                         testData.toObject(testData.getTopicParametersMap(false), TopicParameterGroup.class);
109         XacmlPdpParameterGroup params =
110                 new XacmlPdpParameterGroup("XacmlPdpParameters", "XacmlPdpGroup", rest, policyApiParameters,
111                         topicParameterGroup, apps.getAbsolutePath());
112         final Gson gson = new GsonBuilder().create();
113         File fileParams = appsFolder.newFile("params.json");
114         String jsonParams = gson.toJson(params);
115         LOGGER.info("Creating new params: {}", jsonParams);
116         Files.write(fileParams.toPath(), jsonParams.getBytes());
117         //
118         // Start the service
119         //
120         main = startXacmlPdpService(fileParams);
121         XacmlPdpActivator.getCurrent().startXacmlRestController();
122         //
123         // Make sure it is running
124         //
125         if (!NetworkUtil.isTcpPortOpen("localhost", port, 20, 1000L)) {
126             throw new IllegalStateException("Cannot connect to port " + port);
127         }
128         //
129         // Create a client
130         //
131         client = getNoAuthHttpClient();
132     }
133
134     @AfterClass
135     public static void after() throws PolicyXacmlPdpException {
136         stopXacmlPdpService(main);
137         client.shutdown();
138     }
139
140     @Test
141     public void testDecision_UnsupportedAction() throws Exception {
142
143         LOGGER.info("Running test testDecision_UnsupportedAction");
144
145         DecisionRequest request = new DecisionRequest();
146         request.setOnapName("DROOLS");
147         request.setAction("foo");
148         Map<String, Object> guard = new HashMap<String, Object>();
149         guard.put("actor", "foo");
150         guard.put("recipe", "bar");
151         guard.put("target", "somevnf");
152         guard.put("clname", "phoneyloop");
153         request.setResource(guard);
154
155         ErrorResponse response = getErrorDecision(request);
156         LOGGER.info("Response {}", response);
157         assertThat(response.getResponseCode()).isEqualTo(Status.BAD_REQUEST);
158         assertThat(response.getErrorMessage()).isEqualToIgnoringCase("No application for action foo");
159     }
160
161     @Test
162     public void testDecision_Guard() throws KeyManagementException, NoSuchAlgorithmException,
163         ClassNotFoundException {
164
165         LOGGER.info("Running test testDecision_Guard");
166
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);
176
177         DecisionResponse response = getDecision(request);
178         LOGGER.info("Response {}", response);
179         assertThat(response.getStatus()).isEqualTo("Permit");
180     }
181
182     private static Main startXacmlPdpService(File params) throws PolicyXacmlPdpException {
183         final String[] XacmlPdpConfigParameters = {"-c", params.getAbsolutePath()};
184         return new Main(XacmlPdpConfigParameters);
185     }
186
187     private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
188         main.shutdown();
189     }
190
191     private DecisionResponse getDecision(DecisionRequest request) {
192
193         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
194         Response response = client.post("", entityRequest, Collections.emptyMap());
195
196         assertEquals(200, response.getStatus());
197
198         return HttpClient.getBody(response, DecisionResponse.class);
199     }
200
201     private ErrorResponse getErrorDecision(DecisionRequest request) {
202
203         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
204         Response response = client.post("", entityRequest, Collections.emptyMap());
205
206         assertEquals(400, response.getStatus());
207
208         return HttpClient.getBody(response, ErrorResponse.class);
209     }
210
211     private static HttpClient getNoAuthHttpClient() throws HttpClientConfigException {
212         return HttpClientFactoryInstance.getClientFactory().build(BusTopicParams.builder()
213                 .clientName("testDecisionClient")
214                 .serializationProvider(GsonMessageBodyHandler.class.getName())
215                 .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(port)
216                 .basePath("policy/pdpx/v1/decision")
217                 .userName("healthcheck").password("zb!XztG34").managed(true).build());
218     }
219
220     private static void copy(Path source, Path dest) {
221         try {
222             LOGGER.info("Copying {} to {}", source, dest);
223             Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
224         } catch (IOException e) {
225             LOGGER.error("Failed to copy {} to {}", source, dest);
226         }
227     }
228
229 }