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