3a1e98b14a729a632a5a1d173e7ca6f6c116119c
[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  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdpx.main.rest;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.Assert.assertEquals;
25
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28
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
41 import javax.ws.rs.client.Entity;
42 import javax.ws.rs.core.MediaType;
43 import javax.ws.rs.core.Response;
44 import javax.ws.rs.core.Response.Status;
45
46 import org.junit.AfterClass;
47 import org.junit.BeforeClass;
48 import org.junit.ClassRule;
49 import org.junit.Test;
50 import org.junit.rules.TemporaryFolder;
51 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
52 import org.onap.policy.common.endpoints.http.client.HttpClient;
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.RestServerBuilder;
60 import org.onap.policy.pdpx.main.parameters.RestServerParameters;
61 import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup;
62 import org.onap.policy.pdpx.main.startstop.Main;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 public class TestDecision {
67
68     private static final Logger LOGGER = LoggerFactory.getLogger(TestDecision.class);
69
70     private static Main main;
71     private static HttpClient client;
72
73     @ClassRule
74     public static final TemporaryFolder appsFolder = new TemporaryFolder();
75
76     /**
77      * BeforeClass setup environment.
78      * @throws IOException Cannot create temp apps folder
79      * @throws Exception exception if service does not start
80      */
81     @BeforeClass
82     public static void beforeClass() throws Exception {
83         System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
84         System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
85         //
86         // Copy test directory over of the application directories
87         //
88         Path src = Paths.get("src/test/resources/apps");
89         File apps = appsFolder.newFolder("apps");
90         Files.walk(src).forEach(source -> {
91             copy(source, apps.toPath().resolve(src.relativize(source)));
92         });
93         //
94         // Get the parameters file correct.
95         //
96         RestServerParameters rest = new RestServerParameters(new RestServerBuilder()
97                 .setHost("0.0.0.0").setPort(6969).setUserName("healthcheck").setPassword("zb!XztG34"));
98         XacmlPdpParameterGroup params = new XacmlPdpParameterGroup("XacmlPdpGroup", rest, apps.getAbsolutePath());
99         final Gson gson = new GsonBuilder().create();
100         File fileParams = appsFolder.newFile("params.json");
101         String jsonParams = gson.toJson(params);
102         LOGGER.info("Creating new params: {}", jsonParams);
103         Files.write(fileParams.toPath(), jsonParams.getBytes());
104         //
105         // Start the service
106         //
107         main = startXacmlPdpService(fileParams);
108         //
109         // Make sure it is running
110         //
111         if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 20, 1000L)) {
112             throw new IllegalStateException("Cannot connect to port 6969");
113         }
114         //
115         // Create a client
116         //
117         client = getNoAuthHttpClient();
118     }
119
120     @AfterClass
121     public static void after() throws PolicyXacmlPdpException {
122         stopXacmlPdpService(main);
123     }
124
125     @Test
126     public void testDecision_UnsupportedAction() throws KeyManagementException, NoSuchAlgorithmException,
127         ClassNotFoundException {
128
129         LOGGER.info("Running test testDecision_UnsupportedAction");
130
131         DecisionRequest request = new DecisionRequest();
132         request.setOnapName("DROOLS");
133         request.setAction("foo");
134         Map<String, Object> guard = new HashMap<String, Object>();
135         guard.put("actor", "foo");
136         guard.put("recipe", "bar");
137         guard.put("target", "somevnf");
138         guard.put("clname", "phoneyloop");
139         request.setResource(guard);
140
141         ErrorResponse response = getErrorDecision(request);
142         LOGGER.info("Response {}", response);
143         assertThat(response.getResponseCode()).isEqualTo(Status.BAD_REQUEST);
144         assertThat(response.getErrorMessage()).isEqualToIgnoringCase("No application for action foo");
145     }
146
147     @Test
148     public void testDecision_Guard() throws KeyManagementException, NoSuchAlgorithmException,
149         ClassNotFoundException {
150
151         LOGGER.info("Running test testDecision_Guard");
152
153         DecisionRequest request = new DecisionRequest();
154         request.setOnapName("DROOLS");
155         request.setAction("guard");
156         Map<String, Object> guard = new HashMap<String, Object>();
157         guard.put("actor", "foo");
158         guard.put("recipe", "bar");
159         guard.put("target", "somevnf");
160         guard.put("clname", "phoneyloop");
161         request.setResource(guard);
162
163         DecisionResponse response = getDecision(request);
164         LOGGER.info("Response {}", response);
165         assertThat(response.getStatus()).isEqualTo("Permit");
166     }
167
168     private static Main startXacmlPdpService(File params) {
169         final String[] XacmlPdpConfigParameters = {"-c", params.getAbsolutePath(), "-p",
170             "parameters/topic.properties"};
171         return new Main(XacmlPdpConfigParameters);
172     }
173
174     private static void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
175         main.shutdown();
176     }
177
178     private DecisionResponse getDecision(DecisionRequest request) {
179
180         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
181         Response response = client.post("", entityRequest, Collections.emptyMap());
182
183         assertEquals(200, response.getStatus());
184
185         return HttpClient.getBody(response, DecisionResponse.class);
186     }
187
188     private ErrorResponse getErrorDecision(DecisionRequest request) {
189
190         Entity<DecisionRequest> entityRequest = Entity.entity(request, MediaType.APPLICATION_JSON);
191         Response response = client.post("", entityRequest, Collections.emptyMap());
192
193         assertEquals(400, response.getStatus());
194
195         return HttpClient.getBody(response, ErrorResponse.class);
196     }
197
198     private static HttpClient getNoAuthHttpClient()
199             throws KeyManagementException, NoSuchAlgorithmException, ClassNotFoundException {
200         return HttpClient.factory.build(BusTopicParams.builder()
201                 .clientName("testDecisionClient")
202                 .serializationProvider(GsonMessageBodyHandler.class.getName())
203                 .useHttps(false).allowSelfSignedCerts(false).hostname("localhost").port(6969)
204                 .basePath("policy/pdpx/v1/decision")
205                 .userName("healthcheck").password("zb!XztG34").managed(true).build());
206     }
207
208     private static void copy(Path source, Path dest) {
209         try {
210             LOGGER.info("Copying {} to {}", source, dest);
211             Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
212         } catch (IOException e) {
213             LOGGER.error("Failed to copy {} to {}", source, dest);
214         }
215     }
216
217 }