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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pdpx.main.rest;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertTrue;
25 import static org.junit.Assert.fail;
28 import java.io.IOException;
29 import java.lang.reflect.Constructor;
30 import java.lang.reflect.Modifier;
31 import java.security.SecureRandom;
32 import java.security.cert.X509Certificate;
33 import java.util.Properties;
34 import javax.net.ssl.SSLContext;
35 import javax.net.ssl.TrustManager;
36 import javax.net.ssl.X509TrustManager;
37 import javax.ws.rs.client.Client;
38 import javax.ws.rs.client.ClientBuilder;
39 import javax.ws.rs.client.Invocation;
40 import javax.ws.rs.client.WebTarget;
41 import javax.ws.rs.core.MediaType;
42 import org.glassfish.jersey.client.ClientConfig;
43 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
44 import org.junit.After;
45 import org.junit.BeforeClass;
46 import org.junit.ClassRule;
47 import org.junit.FixMethodOrder;
48 import org.junit.Test;
49 import org.junit.rules.TemporaryFolder;
50 import org.junit.runners.MethodSorters;
51 import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClientException;
52 import org.onap.policy.common.endpoints.report.HealthCheckReport;
53 import org.onap.policy.common.utils.network.NetworkUtil;
54 import org.onap.policy.pdpx.main.PolicyXacmlPdpException;
55 import org.onap.policy.pdpx.main.parameters.CommonTestData;
56 import org.onap.policy.pdpx.main.parameters.RestServerParameters;
57 import org.onap.policy.pdpx.main.rest.model.StatisticsReport;
58 import org.onap.policy.pdpx.main.startstop.Main;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
63 * Class to perform unit test of {@link XacmlPdpRestServer}.
66 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
67 public class TestXacmlPdpRestServer {
69 private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpRestServer.class);
70 private static final String NOT_ALIVE = "not alive";
71 private static final String ALIVE = "alive";
72 private static final String SELF = "self";
73 private static final String NAME = "Policy Xacml PDP";
74 private static final String HEALTHCHECK_ENDPOINT = "healthcheck";
75 private static final String STATISTICS_ENDPOINT = "statistics";
76 private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
78 private XacmlPdpRestServer restServer;
79 private static File applicationPath;
82 public static final TemporaryFolder applicationFolder = new TemporaryFolder();
87 * @throws IOException exception if cannot create temporary folder
90 public static void setUp() throws IOException {
91 System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
92 System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
93 applicationPath = applicationFolder.newFolder();
97 * Method for cleanup after each test.
100 public void teardown() {
102 if (NetworkUtil.isTcpPortOpen("localhost", 6969, 1, 1000L)) {
104 stopXacmlPdpService(main);
108 if (restServer != null) {
113 } catch (IOException | PolicyXacmlPdpException e) {
114 LOGGER.error("teardown failed", e);
115 } catch (InterruptedException ie) {
116 Thread.interrupted();
117 LOGGER.error("teardown failed", ie);
122 public void test1HealthCheckSuccess() throws IOException, InterruptedException, TopicSinkClientException {
123 LOGGER.info("***************************** Running test1HealthCheckSuccess *****************************");
124 main = startXacmlPdpService(true);
125 final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT);
126 final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
127 LOGGER.info("test1HealthCheckSuccess health report {}", report);
128 validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
132 public void test7HealthCheckFailure() throws InterruptedException, IOException {
133 LOGGER.info("***************************** Running test7HealthCheckFailure *****************************");
134 final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
135 restServerParams.setName(CommonTestData.PDPX_GROUP_NAME);
136 restServer = new XacmlPdpRestServer(restServerParams, applicationPath.getAbsolutePath());
138 final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT);
139 final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
140 LOGGER.info("test7HealthCheckFailure health report {}", report);
141 validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report);
142 assertTrue(restServer.isAlive());
143 assertTrue(restServer.toString().startsWith("XacmlPdpRestServer [servers="));
147 public void test2HttpsHealthCheckSuccess() throws Exception {
148 LOGGER.info("**************************** Running test2HttpsHealthCheckSuccess ****************************");
149 main = startXacmlPdpService(false);
150 final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT);
151 final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class);
152 LOGGER.info("test2HttpsHealthCheckSuccess health report {}", report);
153 validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report);
157 public void test4Statistics_200() throws IOException, InterruptedException, TopicSinkClientException {
158 LOGGER.info("***************************** Running test4Statistics_200 *****************************");
159 XacmlPdpStatisticsManager.resetAllStatistics();
160 main = startXacmlPdpService(true);
161 Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
162 StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
163 LOGGER.info("test4Statistics_200 health report {}", report);
164 validateStatisticsReport(report, 0, 200);
165 updateXacmlPdpStatistics();
166 invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
167 report = invocationBuilder.get(StatisticsReport.class);
168 LOGGER.info("test4Statistics_200 health report {}", report);
169 validateStatisticsReport(report, 1, 200);
170 XacmlPdpStatisticsManager.resetAllStatistics();
174 public void test5Statistics_500() throws IOException, InterruptedException {
175 LOGGER.info("***************************** Running test5Statistics_500 *****************************");
176 final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
177 restServerParams.setName(CommonTestData.PDPX_GROUP_NAME);
178 restServer = new XacmlPdpRestServer(restServerParams, applicationPath.getAbsolutePath());
180 final Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT);
181 final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
182 LOGGER.info("test5Statistics_500 health report {}", report);
183 validateStatisticsReport(report, 0, 500);
184 XacmlPdpStatisticsManager.resetAllStatistics();
188 public void test6HttpsStatistic() throws Exception {
189 LOGGER.info("***************************** Running test6HttpsStatistic *****************************");
190 main = startXacmlPdpService(false);
191 final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT);
192 final StatisticsReport report = invocationBuilder.get(StatisticsReport.class);
193 LOGGER.info("test6HttpsStatistic health report {}", report);
194 validateStatisticsReport(report, 0, 200);
198 public void test3StatisticsConstructorIsPrivate() {
199 LOGGER.info("************************* Running test3StatisticsConstructorIsPrivate *************************");
201 final Constructor<XacmlPdpStatisticsManager> constructor =
202 XacmlPdpStatisticsManager.class.getDeclaredConstructor();
203 assertTrue(Modifier.isPrivate(constructor.getModifiers()));
204 constructor.setAccessible(true);
205 constructor.newInstance();
206 fail("Expected an InstantiationException to be thrown");
207 } catch (final Exception exp) {
208 assertTrue(exp.getCause().toString().contains("Instantiation of the class is not allowed"));
212 private Main startXacmlPdpService(final boolean http) throws TopicSinkClientException {
213 final String[] xacmlPdpConfigParameters = new String[4];
215 xacmlPdpConfigParameters[0] = "-c";
216 xacmlPdpConfigParameters[1] = "parameters/XacmlPdpConfigParameters.json";
217 xacmlPdpConfigParameters[2] = "-p";
218 xacmlPdpConfigParameters[3] = "parameters/topic.properties";
220 final Properties systemProps = System.getProperties();
221 systemProps.put("javax.net.ssl.keyStore", KEYSTORE);
222 systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap");
223 System.setProperties(systemProps);
224 xacmlPdpConfigParameters[0] = "-c";
225 xacmlPdpConfigParameters[1] = "parameters/XacmlPdpConfigParameters_Https.json";
226 xacmlPdpConfigParameters[2] = "-p";
227 xacmlPdpConfigParameters[3] = "parameters/topic.properties";
229 return new Main(xacmlPdpConfigParameters);
232 private void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException {
236 private Invocation.Builder sendHttpRequest(final String endpoint) throws IOException, InterruptedException {
237 final ClientConfig clientConfig = new ClientConfig();
239 final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
240 clientConfig.register(feature);
242 final Client client = ClientBuilder.newClient(clientConfig);
243 final WebTarget webTarget = client.target("http://localhost:6969/policy/pdpx/v1/" + endpoint);
245 final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
247 if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 20, 1000L)) {
248 throw new IllegalStateException("Cannot connect to port 6969");
251 return invocationBuilder;
254 private Invocation.Builder sendHttpsRequest(final String endpoint) throws Exception {
256 final TrustManager[] noopTrustManager = new TrustManager[] {new X509TrustManager() {
259 public X509Certificate[] getAcceptedIssuers() {
260 return new X509Certificate[0];
264 public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {}
267 public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {}
270 final SSLContext sc = SSLContext.getInstance("TLSv1.2");
271 sc.init(null, noopTrustManager, new SecureRandom());
272 final ClientBuilder clientBuilder =
273 ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
274 final Client client = clientBuilder.build();
275 final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
276 client.register(feature);
278 final WebTarget webTarget = client.target("https://localhost:6969/policy/pdpx/v1/" + endpoint);
280 final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
282 if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) {
283 throw new IllegalStateException("cannot connect to port 6969");
285 return invocationBuilder;
288 private void updateXacmlPdpStatistics() {
289 XacmlPdpStatisticsManager.updateTotalPoliciesCount();
290 XacmlPdpStatisticsManager.updatePermitDecisionsCount();
291 XacmlPdpStatisticsManager.updateDenyDecisionsCount();
292 XacmlPdpStatisticsManager.updateIndeterminantDecisionsCount();
293 XacmlPdpStatisticsManager.updateNotApplicableDecisionsCount();
296 private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) {
297 assertEquals(code, report.getCode());
298 assertEquals(count, report.getTotalPoliciesCount());
299 assertEquals(count, report.getPermitDecisionsCount());
300 assertEquals(count, report.getDenyDecisionsCount());
301 assertEquals(count, report.getIndeterminantDecisionsCount());
302 assertEquals(count, report.getNotApplicableDecisionsCount());
305 private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code,
306 final String message, final HealthCheckReport report) {
307 assertEquals(name, report.getName());
308 assertEquals(url, report.getUrl());
309 assertEquals(healthy, report.isHealthy());
310 assertEquals(code, report.getCode());
311 assertEquals(message, report.getMessage());