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