b08218827a8c7fa09f77ce3ec5b41c7fb66c19a4
[nonrtric.git] / pmlog / src / main / java / org / oran / pmlog / clients / AsyncRestClientFactory.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2022 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.oran.pmlog.clients;
22
23 import io.netty.handler.ssl.SslContext;
24 import io.netty.handler.ssl.SslContextBuilder;
25 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
26
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.lang.invoke.MethodHandles;
31 import java.security.KeyStore;
32 import java.security.KeyStoreException;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.UnrecoverableKeyException;
35 import java.security.cert.Certificate;
36 import java.security.cert.CertificateException;
37 import java.security.cert.X509Certificate;
38 import java.util.Collections;
39 import java.util.List;
40 import java.util.stream.Collectors;
41
42 import javax.net.ssl.KeyManagerFactory;
43
44 import org.oran.pmlog.configuration.WebClientConfig;
45 import org.oran.pmlog.configuration.WebClientConfig.HttpProxyConfig;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.util.ResourceUtils;
49
50 /**
51  * Factory for a generic reactive REST client.
52  */
53 public class AsyncRestClientFactory {
54     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
55
56     private final SslContextFactory sslContextFactory;
57     private final HttpProxyConfig httpProxyConfig;
58     private final SecurityContext securityContext;
59
60     public AsyncRestClientFactory(WebClientConfig clientConfig, SecurityContext securityContext) {
61         if (clientConfig != null) {
62             this.sslContextFactory = new CachingSslContextFactory(clientConfig);
63             this.httpProxyConfig = clientConfig.getHttpProxyConfig();
64         } else {
65             logger.warn("No configuration for web client defined, HTTPS will not work");
66             this.sslContextFactory = null;
67             this.httpProxyConfig = null;
68         }
69         this.securityContext = securityContext;
70     }
71
72     public AsyncRestClient createRestClientNoHttpProxy(String baseUrl) {
73         return createRestClient(baseUrl, false);
74     }
75
76     public AsyncRestClient createRestClientUseHttpProxy(String baseUrl) {
77         return createRestClient(baseUrl, true);
78     }
79
80     private AsyncRestClient createRestClient(String baseUrl, boolean useHttpProxy) {
81         if (this.sslContextFactory != null) {
82             try {
83                 return new AsyncRestClient(baseUrl, this.sslContextFactory.createSslContext(),
84                         useHttpProxy ? httpProxyConfig : null, this.securityContext);
85             } catch (Exception e) {
86                 String exceptionString = e.toString();
87                 logger.error("Could not init SSL context, reason: {}", exceptionString);
88             }
89         }
90         return new AsyncRestClient(baseUrl, null, httpProxyConfig, this.securityContext);
91     }
92
93     private class SslContextFactory {
94         private final WebClientConfig clientConfig;
95
96         public SslContextFactory(WebClientConfig clientConfig) {
97             this.clientConfig = clientConfig;
98         }
99
100         public SslContext createSslContext() throws UnrecoverableKeyException, NoSuchAlgorithmException,
101                 CertificateException, KeyStoreException, IOException {
102             return this.createSslContext(createKeyManager());
103         }
104
105         private SslContext createSslContext(KeyManagerFactory keyManager)
106                 throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
107             if (this.clientConfig.isTrustStoreUsed()) {
108                 return createSslContextRejectingUntrustedPeers(this.clientConfig.getTrustStore(),
109                         this.clientConfig.getTrustStorePassword(), keyManager);
110             } else {
111                 // Trust anyone
112                 return SslContextBuilder.forClient() //
113                         .keyManager(keyManager) //
114                         .trustManager(InsecureTrustManagerFactory.INSTANCE) //
115                         .build();
116             }
117         }
118
119         private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass,
120                 KeyManagerFactory keyManager)
121                 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
122
123             final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
124             List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
125                     .filter(alias -> isCertificateEntry(trustStore, alias)) //
126                     .map(alias -> getCertificate(trustStore, alias)) //
127                     .collect(Collectors.toList());
128             final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
129
130             return SslContextBuilder.forClient() //
131                     .keyManager(keyManager) //
132                     .trustManager(certificates) //
133                     .build();
134         }
135
136         private boolean isCertificateEntry(KeyStore trustStore, String alias) {
137             try {
138                 return trustStore.isCertificateEntry(alias);
139             } catch (KeyStoreException e) {
140                 logger.error("Error reading truststore {}", e.getMessage());
141                 return false;
142             }
143         }
144
145         private Certificate getCertificate(KeyStore trustStore, String alias) {
146             try {
147                 return trustStore.getCertificate(alias);
148             } catch (KeyStoreException e) {
149                 logger.error("Error reading truststore {}", e.getMessage());
150                 return null;
151             }
152         }
153
154         private KeyManagerFactory createKeyManager() throws NoSuchAlgorithmException, CertificateException, IOException,
155                 UnrecoverableKeyException, KeyStoreException {
156             final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
157             final KeyStore keyStore = KeyStore.getInstance(this.clientConfig.getKeyStoreType());
158             final String keyStoreFile = this.clientConfig.getKeyStore();
159             final String keyStorePassword = this.clientConfig.getKeyStorePassword();
160             final String keyPassword = this.clientConfig.getKeyPassword();
161             try (final InputStream inputStream = new FileInputStream(keyStoreFile)) {
162                 keyStore.load(inputStream, keyStorePassword.toCharArray());
163             }
164             keyManager.init(keyStore, keyPassword.toCharArray());
165             return keyManager;
166         }
167
168         private synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
169                 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
170
171             KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
172             store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
173             return store;
174         }
175     }
176
177     public class CachingSslContextFactory extends SslContextFactory {
178         private SslContext cachedContext = null;
179
180         public CachingSslContextFactory(WebClientConfig clientConfig) {
181             super(clientConfig);
182         }
183
184         @Override
185         public SslContext createSslContext() throws UnrecoverableKeyException, NoSuchAlgorithmException,
186                 CertificateException, KeyStoreException, IOException {
187             if (this.cachedContext == null) {
188                 this.cachedContext = super.createSslContext();
189             }
190             return this.cachedContext;
191
192         }
193     }
194 }