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