0519700df83059d23ea1b3bfcc7cb3a11d435360
[portal/nonrtric-controlpanel.git] / webapp-backend / src / main / java / org / oransc / portal / nonrtric / controlpanel / util / AsyncRestClient.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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.oransc.portal.nonrtric.controlpanel.util;
22
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.lang.invoke.MethodHandles;
26 import java.security.KeyStore;
27 import java.security.KeyStoreException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.cert.Certificate;
30 import java.security.cert.CertificateException;
31 import java.security.cert.X509Certificate;
32 import java.util.Collections;
33 import java.util.List;
34 import java.util.concurrent.atomic.AtomicInteger;
35 import java.util.stream.Collectors;
36 import org.immutables.value.Value;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.http.MediaType;
40 import org.springframework.http.ResponseEntity;
41 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
42 import org.springframework.util.ResourceUtils;
43 import org.springframework.web.reactive.function.client.ExchangeStrategies;
44 import org.springframework.web.reactive.function.client.WebClient;
45 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
46 import org.springframework.web.reactive.function.client.WebClientResponseException;
47 import io.netty.channel.ChannelOption;
48 import io.netty.handler.ssl.SslContext;
49 import io.netty.handler.ssl.SslContextBuilder;
50 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
51 import io.netty.handler.timeout.ReadTimeoutHandler;
52 import io.netty.handler.timeout.WriteTimeoutHandler;
53 import reactor.core.publisher.Mono;
54 import reactor.netty.http.client.HttpClient;
55 import reactor.netty.resources.ConnectionProvider;
56 import reactor.netty.tcp.TcpClient;
57
58 /**
59  * Generic reactive REST client.
60  */
61 public class AsyncRestClient {
62
63     @Value.Immutable
64     @Value.Style(redactedMask = "####")
65     public interface WebClientConfig {
66         public boolean isTrustStoreUsed();
67
68         @Value.Redacted
69         public String trustStorePassword();
70
71         public String trustStore();
72     }
73
74     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
75     private WebClient webClient = null;
76     private final String baseUrl;
77     private static final AtomicInteger sequenceNumber = new AtomicInteger();
78     private final WebClientConfig clientConfig;
79     static KeyStore clientTrustStore = null;
80
81     public AsyncRestClient(String baseUrl) {
82         this(baseUrl,
83             ImmutableWebClientConfig.builder().isTrustStoreUsed(false).trustStore("").trustStorePassword("").build());
84     }
85
86     public AsyncRestClient(String baseUrl, WebClientConfig config) {
87         this.baseUrl = baseUrl;
88         this.clientConfig = config;
89     }
90
91     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
92         Object traceTag = createTraceTag();
93         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
94         logger.trace("{} PUT body: {}", traceTag, body);
95         return getWebClient() //
96             .flatMap(client -> {
97                 RequestHeadersSpec<?> request = client.put() //
98                     .uri(uri) //
99                     .contentType(MediaType.APPLICATION_JSON) //
100                     .bodyValue(body);
101                 return retrieve(traceTag, request);
102             });
103     }
104
105     public Mono<ResponseEntity<String>> putForEntity(String uri) {
106         Object traceTag = createTraceTag();
107         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
108         logger.trace("{} PUT body: <empty>", traceTag);
109         return getWebClient() //
110             .flatMap(client -> {
111                 RequestHeadersSpec<?> request = client.put() //
112                     .uri(uri);
113                 return retrieve(traceTag, request);
114             });
115     }
116
117     public Mono<String> put(String uri, String body) {
118         return putForEntity(uri, body) //
119             .flatMap(this::toBody);
120     }
121
122     public Mono<ResponseEntity<String>> getForEntity(String uri) {
123         Object traceTag = createTraceTag();
124         logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
125         return getWebClient() //
126             .flatMap(client -> {
127                 RequestHeadersSpec<?> request = client.get().uri(uri);
128                 return retrieve(traceTag, request);
129             });
130     }
131
132     public Mono<String> get(String uri) {
133         return getForEntity(uri) //
134             .flatMap(this::toBody);
135     }
136
137     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
138         Object traceTag = createTraceTag();
139         logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
140         return getWebClient() //
141             .flatMap(client -> {
142                 RequestHeadersSpec<?> request = client.delete().uri(uri);
143                 return retrieve(traceTag, request);
144             });
145     }
146
147     public Mono<String> delete(String uri) {
148         return deleteForEntity(uri) //
149             .flatMap(this::toBody);
150     }
151
152     private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
153         final Class<String> clazz = String.class;
154         return request.retrieve() //
155             .toEntity(clazz) //
156             .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody())) //
157             .doOnError(throwable -> onHttpError(traceTag, throwable));
158     }
159
160     private static Object createTraceTag() {
161         return sequenceNumber.incrementAndGet();
162     }
163
164     private void onHttpError(Object traceTag, Throwable t) {
165         if (t instanceof WebClientResponseException) {
166             WebClientResponseException exception = (WebClientResponseException) t;
167             logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
168                 exception.getResponseBodyAsString());
169         } else {
170             logger.debug("{} HTTP error: {}", traceTag, t.getMessage());
171         }
172     }
173
174     private Mono<String> toBody(ResponseEntity<String> entity) {
175         if (entity.getBody() == null) {
176             return Mono.just("");
177         } else {
178             return Mono.just(entity.getBody());
179         }
180     }
181
182     private boolean isCertificateEntry(KeyStore trustStore, String alias) {
183         try {
184             return trustStore.isCertificateEntry(alias);
185         } catch (KeyStoreException e) {
186             logger.error("Error reading truststore {}", e.getMessage());
187             return false;
188         }
189     }
190
191     private Certificate getCertificate(KeyStore trustStore, String alias) {
192         try {
193             return trustStore.getCertificate(alias);
194         } catch (KeyStoreException e) {
195             logger.error("Error reading truststore {}", e.getMessage());
196             return null;
197         }
198     }
199
200     private static synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
201         throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
202         if (clientTrustStore == null) {
203             KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
204             store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
205             clientTrustStore = store;
206         }
207         return clientTrustStore;
208     }
209
210     private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass)
211         throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
212
213         final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
214         List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
215             .filter(alias -> isCertificateEntry(trustStore, alias)) //
216             .map(alias -> getCertificate(trustStore, alias)) //
217             .collect(Collectors.toList());
218         final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
219
220         return SslContextBuilder.forClient() //
221             .trustManager(certificates) //
222             .build();
223     }
224
225     private SslContext createSslContext()
226         throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
227         if (this.clientConfig.isTrustStoreUsed()) {
228             return createSslContextRejectingUntrustedPeers(this.clientConfig.trustStore(),
229                 this.clientConfig.trustStorePassword());
230         } else {
231             // Trust anyone
232             return SslContextBuilder.forClient() //
233                 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
234                 .build();
235         }
236     }
237
238     private WebClient createWebClient(String baseUrl, SslContext sslContext) {
239         ConnectionProvider connectionProvider = ConnectionProvider.newConnection();
240         TcpClient tcpClient = TcpClient.create(connectionProvider) //
241             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
242             .secure(c -> c.sslContext(sslContext)) //
243
244             .doOnConnected(connection -> {
245                 connection.addHandlerLast(new ReadTimeoutHandler(30));
246                 connection.addHandlerLast(new WriteTimeoutHandler(30));
247             });
248         HttpClient httpClient = HttpClient.from(tcpClient);
249         ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
250
251         ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
252             .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
253             .build();
254
255         return WebClient.builder() //
256             .clientConnector(connector) //
257             .baseUrl(baseUrl) //
258             .exchangeStrategies(exchangeStrategies) //
259             .build();
260     }
261
262     private Mono<WebClient> getWebClient() {
263         if (this.webClient == null) {
264             try {
265                 SslContext sslContext = createSslContext();
266                 this.webClient = createWebClient(this.baseUrl, sslContext);
267             } catch (Exception e) {
268                 logger.error("Could not create WebClient {}", e.getMessage());
269                 return Mono.error(e);
270             }
271         }
272         return Mono.just(this.webClient);
273     }
274
275 }