2 * ========================LICENSE_START=================================
5 * Copyright (C) 2023 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oran.pmproducer.clients;
23 import io.netty.handler.ssl.SslContext;
24 import io.netty.handler.ssl.SslContextBuilder;
25 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
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;
42 import javax.net.ssl.KeyManagerFactory;
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;
52 * Factory for a generic reactive REST client.
54 public class AsyncRestClientFactory {
55 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
57 private final SslContextFactory sslContextFactory;
58 private final HttpProxyConfig httpProxyConfig;
59 private final SecurityContext securityContext;
61 public AsyncRestClientFactory(WebClientConfig clientConfig, SecurityContext securityContext) {
62 if (clientConfig != null) {
63 this.sslContextFactory = new CachingSslContextFactory(clientConfig);
64 this.httpProxyConfig = clientConfig.getHttpProxyConfig();
66 logger.warn("No configuration for web client defined, HTTPS will not work");
67 this.sslContextFactory = null;
68 this.httpProxyConfig = null;
70 this.securityContext = securityContext;
73 public AsyncRestClient createRestClientNoHttpProxy(String baseUrl) {
74 return createRestClient(baseUrl, false);
77 public AsyncRestClient createRestClientUseHttpProxy(String baseUrl) {
78 return createRestClient(baseUrl, true);
81 private AsyncRestClient createRestClient(String baseUrl, boolean useHttpProxy) {
82 if (this.sslContextFactory != null) {
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);
91 return new AsyncRestClient(baseUrl, null, httpProxyConfig, this.securityContext);
94 private class SslContextFactory {
95 private final WebClientConfig clientConfig;
97 public SslContextFactory(WebClientConfig clientConfig) {
98 this.clientConfig = clientConfig;
101 public SslContext createSslContext() throws UnrecoverableKeyException, NoSuchAlgorithmException,
102 CertificateException, KeyStoreException, IOException {
103 return this.createSslContext(createKeyManager());
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);
113 return SslContextBuilder.forClient() //
114 .keyManager(keyManager) //
115 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
120 @SuppressWarnings("java:S6204")
121 private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass,
122 KeyManagerFactory keyManager)
123 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
125 final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
126 List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
127 .filter(alias -> isCertificateEntry(trustStore, alias)) //
128 .map(alias -> getCertificate(trustStore, alias)) //
129 .collect(Collectors.toList());
130 final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
132 return SslContextBuilder.forClient() //
133 .keyManager(keyManager) //
134 .trustManager(certificates) //
138 private boolean isCertificateEntry(KeyStore trustStore, String alias) {
140 return trustStore.isCertificateEntry(alias);
141 } catch (KeyStoreException e) {
142 logger.error("Error reading truststore {}", e.getMessage());
147 private Certificate getCertificate(KeyStore trustStore, String alias) {
149 return trustStore.getCertificate(alias);
150 } catch (KeyStoreException e) {
151 logger.error("Error reading truststore {}", e.getMessage());
156 private KeyManagerFactory createKeyManager() throws NoSuchAlgorithmException, CertificateException, IOException,
157 UnrecoverableKeyException, KeyStoreException {
158 final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
159 final KeyStore keyStore = KeyStore.getInstance(this.clientConfig.getKeyStoreType());
160 final String keyStoreFile = this.clientConfig.getKeyStore();
161 final String keyStorePassword = this.clientConfig.getKeyStorePassword();
162 final String keyPassword = this.clientConfig.getKeyPassword();
163 try (final InputStream inputStream = new FileInputStream(keyStoreFile)) {
164 keyStore.load(inputStream, keyStorePassword.toCharArray());
166 keyManager.init(keyStore, keyPassword.toCharArray());
170 private synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
171 throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
173 KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
174 store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
179 public class CachingSslContextFactory extends SslContextFactory {
180 private SslContext cachedContext = null;
182 public CachingSslContextFactory(WebClientConfig clientConfig) {
187 public SslContext createSslContext() throws UnrecoverableKeyException, NoSuchAlgorithmException,
188 CertificateException, KeyStoreException, IOException {
189 if (this.cachedContext == null) {
190 this.cachedContext = super.createSslContext();
192 return this.cachedContext;