Fix for Penetration test _ Session and cookie management
[vid.git] / vid-app-common / src / test / java / org / onap / vid / asdc / rest / SdcRestClientITTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2018 - 2019 Nokia Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.asdc.rest;
22
23 import static com.xebialabs.restito.semantics.Action.ok;
24 import static com.xebialabs.restito.semantics.Action.stringContent;
25 import static org.apache.http.client.config.RequestConfig.custom;
26 import static org.hamcrest.MatcherAssert.assertThat;
27 import static org.hamcrest.Matchers.equalToIgnoringCase;
28 import static org.hamcrest.Matchers.is;
29 import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
30 import static org.hamcrest.collection.IsMapContaining.hasKey;
31 import static org.junit.Assert.assertTrue;
32 import static org.mockito.Mockito.mock;
33 import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID;
34
35 import com.fasterxml.jackson.core.JsonProcessingException;
36 import com.xebialabs.restito.semantics.Call;
37 import java.io.IOException;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.security.GeneralSecurityException;
41 import java.util.Collections;
42 import java.util.Optional;
43 import java.util.UUID;
44 import javax.net.ssl.SSLContext;
45 import org.apache.http.config.Registry;
46 import org.apache.http.config.RegistryBuilder;
47 import org.apache.http.conn.socket.ConnectionSocketFactory;
48 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
49 import org.apache.http.conn.ssl.SSLContextBuilder;
50 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
51 import org.apache.http.impl.client.CloseableHttpClient;
52 import org.apache.http.impl.client.HttpClientBuilder;
53 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
54 import org.junit.AfterClass;
55 import org.junit.BeforeClass;
56 import org.junit.Test;
57 import org.onap.vid.asdc.AsdcCatalogException;
58 import org.onap.vid.asdc.beans.Service;
59 import org.onap.vid.client.SyncRestClient;
60 import org.onap.vid.testUtils.StubServerUtil;
61 import org.onap.vid.utils.Logging;
62
63
64 public class SdcRestClientITTest {
65     private static final String[] SUPPORTED_SSL_VERSIONS = {"TLSv1", "TLSv1.2"};
66     private static StubServerUtil stubServer;
67     private static SdcRestClient sdcRestClient;
68
69     @BeforeClass
70     public static void setUpClass() throws GeneralSecurityException {
71         stubServer = new StubServerUtil();
72         stubServer.runSecuredServer();
73         SyncRestClient syncRestClient = new SyncRestClient(createNaiveHttpClient(), mock(Logging.class));
74         String serverUrl = stubServer.constructTargetUrl("https", "");
75         sdcRestClient = new SdcRestClient(serverUrl, "", syncRestClient, mock(Logging.class));
76     }
77
78     @AfterClass
79     public static void tearDown() {
80         stubServer.stopServer();
81     }
82
83     @Test
84     public void shouldDownloadToscaArtifactUsingSecuredEndpoint() throws AsdcCatalogException, IOException {
85         UUID uuid = UUID.randomUUID();
86         String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/toscaModel", uuid);
87
88         stubServer.prepareGetCall(
89                 expectedEndpoint, stringContent("sampleFileContent"), ok(), "application/octet-stream");
90
91
92         Path serviceToscaModel = sdcRestClient.getServiceToscaModel(uuid);
93         serviceToscaModel.toFile().deleteOnExit();
94
95
96         assertThat(Files.readAllLines(serviceToscaModel), contains("sampleFileContent"));
97         assertThatRequestHasRequiredHeaders(expectedEndpoint);
98     }
99
100     @Test
101     public void shouldGetServiceDetailsUsingSecuredEndpoint() throws AsdcCatalogException, JsonProcessingException {
102         UUID uuid = UUID.randomUUID();
103         String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/metadata", uuid);
104         Service expectedService = getExpectedService(uuid.toString());
105
106
107         stubServer.prepareGetCall(expectedEndpoint, expectedService, ok());
108
109
110         Service actualService = sdcRestClient.getService(uuid);
111
112
113         assertThat(actualService, is(expectedService));
114         assertThatRequestHasRequiredHeaders(expectedEndpoint);
115     }
116
117     private void assertThatRequestHasRequiredHeaders(String expectedEndpoint) {
118         Optional<Call> first = stubServer
119                 .getServerCalls()
120                 .stream()
121                 .filter(x -> x.getUri().contains(expectedEndpoint))
122                 .findFirst();
123
124         assertTrue(first.isPresent());
125
126         assertThat(first.get().getHeaders(), hasKey(equalToIgnoringCase(X_ECOMP_INSTANCE_ID)));
127     }
128
129     private Service getExpectedService(String stringId) {
130         return new Service.ServiceBuilder().setUuid(stringId)
131                 .setInvariantUUID(stringId)
132                 .setCategory("sampleCategory")
133                 .setVersion("sampleVersion")
134                 .setName( "sampleName")
135                 .setDistributionStatus("sampleDistStatus")
136                 .setToscaModelURL("sampleToscaUrl")
137                 .setLifecycleState(Service.LifecycleState.CERTIFIED)
138                 .setArtifacts(Collections.emptyList())
139                 .setResources(Collections.emptyList()).build();
140     }
141
142
143     private static CloseableHttpClient createNaiveHttpClient() throws GeneralSecurityException {
144         final SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
145                 .build();
146
147         final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context, SUPPORTED_SSL_VERSIONS,
148                 null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
149         Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
150                 .register("https", socketFactory)
151                 .build();
152
153         return HttpClientBuilder.create()
154                 .setDefaultRequestConfig(custom().setConnectionRequestTimeout(10000).build())
155                 .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
156                 .setSSLSocketFactory(socketFactory).build();
157     }
158 }