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