Upgrade spring-boot to 2.7.X in model-loader
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / restclient / HttpsBabelServiceClient.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2019 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.modelloader.restclient;
23
24 import com.google.gson.Gson;
25 import com.google.gson.reflect.TypeToken;
26 import com.google.json.JsonSanitizer;
27 import com.sun.jersey.api.client.Client; // NOSONAR
28 import com.sun.jersey.api.client.ClientResponse;
29 import com.sun.jersey.api.client.WebResource;
30 import com.sun.jersey.api.client.config.DefaultClientConfig;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.security.KeyManagementException;
36 import java.security.KeyStore;
37 import java.security.KeyStoreException;
38 import java.security.NoSuchAlgorithmException;
39 import java.security.UnrecoverableKeyException;
40 import java.security.cert.CertificateException;
41 import java.security.cert.X509Certificate;
42 import java.time.ZonedDateTime;
43 import java.time.format.DateTimeFormatter;
44 import java.util.Base64;
45 import java.util.Collections;
46 import java.util.List;
47 import java.util.Objects;
48 import javax.net.ssl.HttpsURLConnection;
49 import javax.net.ssl.KeyManagerFactory;
50 import javax.net.ssl.SSLContext;
51 import javax.net.ssl.TrustManager;
52 import javax.net.ssl.TrustManagerFactory;
53 import javax.net.ssl.X509TrustManager;
54 import javax.ws.rs.core.Response;
55 import org.json.JSONException;
56 import org.json.JSONObject;
57 import org.onap.aai.babel.service.data.BabelArtifact;
58 import org.onap.aai.cl.api.LogFields;
59 import org.onap.aai.cl.api.LogLine;
60 import org.onap.aai.cl.api.Logger;
61 import org.onap.aai.cl.eelf.LoggerFactory;
62 import org.onap.aai.cl.mdc.MdcContext;
63 import org.onap.aai.cl.mdc.MdcOverride;
64 import org.onap.aai.modelloader.config.ModelLoaderConfig;
65 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
66
67 /**
68  * HTTPS Client for interfacing with Babel.
69  *
70  */
71 public class HttpsBabelServiceClient implements BabelServiceClient {
72
73     private static final Logger logger = LoggerFactory.getInstance().getLogger(HttpsBabelServiceClient.class);
74     private static final Logger metricsLogger =
75             LoggerFactory.getInstance().getMetricsLogger(HttpsBabelServiceClient.class);
76     private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
77
78     private static final String SSL_PROTOCOL = "TLS";
79     private static final String KEYSTORE_ALGORITHM = "SunX509";
80     private static final String KEYSTORE_TYPE = "PKCS12";
81
82     private final ModelLoaderConfig config;
83     private final Client client;
84
85     /**
86      * @param config
87      * @throws NoSuchAlgorithmException
88      * @throws KeyStoreException
89      * @throws CertificateException
90      * @throws IOException
91      * @throws UnrecoverableKeyException
92      * @throws KeyManagementException
93      * @throws BabelServiceClientException
94      */
95     public HttpsBabelServiceClient(ModelLoaderConfig config)
96             throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
97             UnrecoverableKeyException, KeyManagementException, BabelServiceClientException {
98         this.config = config;
99
100         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client");
101         //Initialize SSL Context only if SSL is enabled
102         if (config.useHttpsWithBabel()) {
103             SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
104             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
105             KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
106
107             String clientCertPassword = config.getBabelKeyStorePassword();
108
109             char[] pwd = null;
110             if (clientCertPassword != null) {
111                 pwd = clientCertPassword.toCharArray();
112             }
113
114             TrustManager[] trustManagers = getTrustManagers();
115
116             String clientCertFileName = config.getBabelKeyStorePath();
117             if (clientCertFileName == null) {
118                 ctx.init(null, trustManagers, null);
119             } else {
120                 InputStream fin = Files.newInputStream(Paths.get(clientCertFileName));
121                 keyStore.load(fin, pwd);
122                 kmf.init(keyStore, pwd);
123                 ctx.init(kmf.getKeyManagers(), trustManagers, null);
124             }
125
126             logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
127
128             HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
129             HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
130         }
131
132         client = Client.create(new DefaultClientConfig());
133
134         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
135     }
136
137     private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
138             IOException, BabelServiceClientException {
139         TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
140         // Using null here initializes the TMF with the default trust store.
141         tmf.init((KeyStore) null);
142
143         // Create a new Trust Manager from the local trust store.
144         String trustStoreFile = config.getBabelTrustStorePath();
145         if (trustStoreFile == null) {
146             throw new BabelServiceClientException("No Babel trust store defined");
147         }
148         try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) {
149             KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
150             myTrustStore.load(myKeys, config.getBabelTrustStorePassword().toCharArray());
151             tmf.init(myTrustStore);
152         }
153         X509TrustManager localTm = findX509TrustManager(tmf);
154
155         // Create a custom trust manager that wraps both our trust store and the default.
156         final X509TrustManager finalLocalTm = localTm;
157
158         // Find the default trust manager.
159         final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
160
161         return new TrustManager[] {new X509TrustManager() {
162             @Override
163             public X509Certificate[] getAcceptedIssuers() {
164                 return defaultTrustManager.getAcceptedIssuers();
165             }
166
167             @Override
168             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
169                 try {
170                     finalLocalTm.checkServerTrusted(chain, authType);
171                 } catch (CertificateException e) { // NOSONAR
172                     defaultTrustManager.checkServerTrusted(chain, authType);
173                 }
174             }
175
176             @Override
177             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
178                 defaultTrustManager.checkClientTrusted(chain, authType);
179             }
180         }};
181     }
182
183     private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
184         X509TrustManager trustManager = null;
185         for (TrustManager tm : tmf.getTrustManagers()) {
186             if (tm instanceof X509TrustManager) {
187                 trustManager = (X509TrustManager) tm;
188                 break;
189             }
190         }
191         return trustManager;
192     }
193
194     /**
195      * @param artifactPayload
196      * @param artifactName
197      * @param artifactVersion
198      * @param transactionId
199      * @return
200      * @throws BabelServiceClientException
201      * @throws JSONException
202      */
203     @Override
204     public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
205             String transactionId) throws BabelServiceClientException {
206         Objects.requireNonNull(artifactPayload);
207
208         String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
209
210         JSONObject obj = new JSONObject();
211         try {
212             obj.put("csar", encodedPayload);
213             obj.put("artifactVersion", artifactVersion);
214             obj.put("artifactName", artifactName);
215         } catch (JSONException ex) {
216             throw new BabelServiceClientException(ex);
217         }
218
219         if (logger.isInfoEnabled()) {
220             logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
221                     + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
222         }
223
224         MdcOverride override = new MdcOverride();
225         override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter));
226
227         String resourceUrl = config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl();
228         WebResource webResource = client.resource(resourceUrl);
229         ClientResponse response = webResource.type("application/json")
230                 .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
231                 .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
232                 .post(ClientResponse.class, obj.toString());
233         String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
234
235         if (logger.isDebugEnabled()) {
236             logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
237                     "Babel response " + response.getStatus() + " " + sanitizedJson);
238         }
239
240         metricsLogger.info(ModelLoaderMsgs.BABEL_REST_REQUEST, new LogFields() //
241                 .setField(LogLine.DefinedFields.TARGET_ENTITY, "Babel")
242                 .setField(LogLine.DefinedFields.STATUS_CODE,
243                         Response.Status.fromStatusCode(response.getStatus()).getFamily()
244                                 .equals(Response.Status.Family.SUCCESSFUL) ? "COMPLETE" : "ERROR")
245                 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
246                 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusInfo().toString()), //
247                 override, response.toString());
248
249         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
250             throw new BabelServiceClientException(sanitizedJson);
251         }
252
253         return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());
254     }
255 }