073fc931078b6d2016eec0f95e64c09cb92fc79f
[so.git] / adapters / mso-vnfm-adapter / mso-vnfm-etsi-adapter / src / main / java / org / onap / so / adapters / vnfmadapter / extclients / vnfm / VnfmServiceProviderConfiguration.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.adapters.vnfmadapter.extclients.vnfm;
22
23 import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE;
24 import java.io.IOException;
25 import java.security.KeyManagementException;
26 import java.security.KeyStore;
27 import java.security.KeyStoreException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.UnrecoverableKeyException;
30 import java.security.cert.CertificateException;
31 import java.util.ListIterator;
32 import java.util.Map;
33 import java.util.UUID;
34 import java.util.concurrent.ConcurrentHashMap;
35 import javax.net.ssl.SSLContext;
36 import org.apache.commons.lang3.StringUtils;
37 import org.apache.http.client.HttpClient;
38 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
39 import org.apache.http.impl.client.HttpClients;
40 import org.apache.http.ssl.SSLContextBuilder;
41 import org.onap.aai.domain.yang.EsrSystemInfo;
42 import org.onap.aai.domain.yang.EsrVnfm;
43 import org.onap.logging.filter.spring.SpringClientPayloadFilter;
44 import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration;
45 import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
46 import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter;
47 import org.onap.so.rest.service.HttpRestServiceProvider;
48 import org.onap.so.rest.service.HttpRestServiceProviderImpl;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.beans.factory.annotation.Qualifier;
53 import org.springframework.beans.factory.annotation.Value;
54 import org.springframework.context.annotation.Configuration;
55 import org.springframework.core.io.Resource;
56 import org.springframework.http.client.BufferingClientHttpRequestFactory;
57 import org.springframework.http.client.ClientHttpRequestInterceptor;
58 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
59 import org.springframework.security.oauth2.client.OAuth2RestTemplate;
60 import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
61 import org.springframework.web.client.RestTemplate;
62
63 /**
64  * Configures the HttpRestServiceProvider for REST call to a VNFM.
65  */
66 @Configuration
67 public class VnfmServiceProviderConfiguration extends AbstractServiceProviderConfiguration {
68
69     private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderConfiguration.class);
70     private Map<String, HttpRestServiceProvider> mapOfVnfmIdToHttpRestServiceProvider = new ConcurrentHashMap<>();
71
72     @Value("${http.client.ssl.trust-store:#{null}}")
73     private Resource trustStore;
74     @Value("${http.client.ssl.trust-store-password:#{null}}")
75     private String trustStorePassword;
76
77     @Value("${server.ssl.key-store:#{null}}")
78     private Resource keyStoreResource;
79     @Value("${server.ssl.key--store-password:#{null}}")
80     private String keyStorePassword;
81
82     /**
83      * This property is only intended to be temporary until the AAI schema is updated to support setting the endpoint
84      */
85     @Value("${vnfmadapter.temp.vnfm.oauth.endpoint:#{null}}")
86     private String oauthEndpoint;
87
88     @Qualifier(CONFIGURABLE_REST_TEMPLATE)
89     @Autowired()
90     private RestTemplate defaultRestTemplate;
91
92     public HttpRestServiceProvider getHttpRestServiceProvider(final EsrVnfm vnfm) {
93         if (!mapOfVnfmIdToHttpRestServiceProvider.containsKey(vnfm.getVnfmId())) {
94             mapOfVnfmIdToHttpRestServiceProvider.put(vnfm.getVnfmId(), createHttpRestServiceProvider(vnfm));
95         }
96         return mapOfVnfmIdToHttpRestServiceProvider.get(vnfm.getVnfmId());
97     }
98
99     private HttpRestServiceProvider createHttpRestServiceProvider(final EsrVnfm vnfm) {
100         final RestTemplate restTemplate = createRestTemplate(vnfm);
101         setGsonMessageConverter(restTemplate);
102         if (trustStore != null) {
103             setTrustStore(restTemplate);
104         }
105         return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider());
106     }
107
108     private RestTemplate createRestTemplate(final EsrVnfm vnfm) {
109         if (vnfm != null) {
110             for (final EsrSystemInfo esrSystemInfo : vnfm.getEsrSystemInfoList().getEsrSystemInfo()) {
111                 if (!StringUtils.isEmpty(esrSystemInfo.getUserName())
112                         && !StringUtils.isEmpty(esrSystemInfo.getPassword())) {
113                     return createOAuth2RestTemplate(esrSystemInfo);
114                 }
115             }
116         }
117         return defaultRestTemplate;
118     }
119
120     private OAuth2RestTemplate createOAuth2RestTemplate(final EsrSystemInfo esrSystemInfo) {
121         logger.debug("Getting OAuth2RestTemplate ...");
122         final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
123         resourceDetails.setId(UUID.randomUUID().toString());
124         resourceDetails.setClientId(esrSystemInfo.getUserName());
125         resourceDetails.setClientSecret(esrSystemInfo.getPassword());
126         resourceDetails.setAccessTokenUri(
127                 oauthEndpoint == null ? esrSystemInfo.getServiceUrl().replace("vnflcm/v1", "oauth/token")
128                         : oauthEndpoint);
129         resourceDetails.setGrantType("client_credentials");
130         return new OAuth2RestTemplate(resourceDetails);
131     }
132
133     private void setTrustStore(final RestTemplate restTemplate) {
134         SSLContext sslContext;
135         try {
136             if (keyStoreResource != null) {
137                 KeyStore keystore = KeyStore.getInstance("pkcs12");
138                 keystore.load(keyStoreResource.getInputStream(), keyStorePassword.toCharArray());
139                 sslContext =
140                         new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray())
141                                 .loadKeyMaterial(keystore, keyStorePassword.toCharArray()).build();
142             } else {
143                 sslContext = new SSLContextBuilder()
144                         .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build();
145             }
146             logger.info("Setting truststore: {}", trustStore.getURL());
147             final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
148             final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
149             final HttpComponentsClientHttpRequestFactory factory =
150                     new HttpComponentsClientHttpRequestFactory(httpClient);
151             restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));
152         } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
153                 | IOException | UnrecoverableKeyException exception) {
154             logger.error("Error reading truststore, TLS connection to VNFM will fail.", exception);
155         }
156     }
157
158     private void removeSpringClientFilter(final RestTemplate restTemplate) {
159         ListIterator<ClientHttpRequestInterceptor> interceptorIterator = restTemplate.getInterceptors().listIterator();
160         while (interceptorIterator.hasNext()) {
161             ClientHttpRequestInterceptor interceptor = interceptorIterator.next();
162             if (interceptor instanceof SOSpringClientFilter || interceptor instanceof SpringClientPayloadFilter) {
163                 interceptorIterator.remove();
164             }
165         }
166     }
167
168 }