805fe342e36de838b2fd4f8edf30041760b3d82b
[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
102         SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
103         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
104         KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
105
106         String clientCertPassword = config.getBabelKeyStorePassword();
107
108         char[] pwd = null;
109         if (clientCertPassword != null) {
110             pwd = clientCertPassword.toCharArray();
111         }
112
113         TrustManager[] trustManagers = getTrustManagers();
114
115         String clientCertFileName = config.getBabelKeyStorePath();
116         if (clientCertFileName == null) {
117             ctx.init(null, trustManagers, null);
118         } else {
119             InputStream fin = Files.newInputStream(Paths.get(clientCertFileName));
120             keyStore.load(fin, pwd);
121             kmf.init(keyStore, pwd);
122             ctx.init(kmf.getKeyManagers(), trustManagers, null);
123         }
124
125         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
126
127         HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
128         HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
129
130         client = Client.create(new DefaultClientConfig());
131
132         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
133     }
134
135     private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
136             IOException, BabelServiceClientException {
137         TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
138         // Using null here initializes the TMF with the default trust store.
139         tmf.init((KeyStore) null);
140
141         // Create a new Trust Manager from the local trust store.
142         String trustStoreFile = config.getBabelTrustStorePath();
143         if (trustStoreFile == null) {
144             throw new BabelServiceClientException("No Babel trust store defined");
145         }
146         try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) {
147             KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
148             myTrustStore.load(myKeys, config.getBabelTrustStorePassword().toCharArray());
149             tmf.init(myTrustStore);
150         }
151         X509TrustManager localTm = findX509TrustManager(tmf);
152
153         // Create a custom trust manager that wraps both our trust store and the default.
154         final X509TrustManager finalLocalTm = localTm;
155
156         // Find the default trust manager.
157         final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
158
159         return new TrustManager[] {new X509TrustManager() {
160             @Override
161             public X509Certificate[] getAcceptedIssuers() {
162                 return defaultTrustManager.getAcceptedIssuers();
163             }
164
165             @Override
166             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
167                 try {
168                     finalLocalTm.checkServerTrusted(chain, authType);
169                 } catch (CertificateException e) { // NOSONAR
170                     defaultTrustManager.checkServerTrusted(chain, authType);
171                 }
172             }
173
174             @Override
175             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
176                 defaultTrustManager.checkClientTrusted(chain, authType);
177             }
178         }};
179     }
180
181     private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
182         X509TrustManager trustManager = null;
183         for (TrustManager tm : tmf.getTrustManagers()) {
184             if (tm instanceof X509TrustManager) {
185                 trustManager = (X509TrustManager) tm;
186                 break;
187             }
188         }
189         return trustManager;
190     }
191
192     /**
193      * @param artifactPayload
194      * @param artifactName
195      * @param artifactVersion
196      * @param transactionId
197      * @return
198      * @throws BabelServiceClientException
199      * @throws JSONException
200      */
201     @Override
202     public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
203             String transactionId) throws BabelServiceClientException {
204         Objects.requireNonNull(artifactPayload);
205
206         String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
207
208         JSONObject obj = new JSONObject();
209         try {
210             obj.put("csar", encodedPayload);
211             obj.put("artifactVersion", artifactVersion);
212             obj.put("artifactName", artifactName);
213         } catch (JSONException ex) {
214             throw new BabelServiceClientException(ex);
215         }
216
217         if (logger.isInfoEnabled()) {
218             logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
219                     + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
220         }
221
222         MdcOverride override = new MdcOverride();
223         override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter));
224
225         WebResource webResource = client.resource(config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl());
226         ClientResponse response = webResource.type("application/json")
227                 .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
228                 .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
229                 .post(ClientResponse.class, obj.toString());
230         String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
231
232         if (logger.isDebugEnabled()) {
233             logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
234                     "Babel response " + response.getStatus() + " " + sanitizedJson);
235         }
236
237         metricsLogger.info(ModelLoaderMsgs.BABEL_REST_REQUEST, new LogFields() //
238                 .setField(LogLine.DefinedFields.TARGET_ENTITY, "Babel")
239                 .setField(LogLine.DefinedFields.STATUS_CODE,
240                         Response.Status.fromStatusCode(response.getStatus()).getFamily()
241                                 .equals(Response.Status.Family.SUCCESSFUL) ? "COMPLETE" : "ERROR")
242                 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
243                 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusInfo().toString()), //
244                 override, response.toString());
245
246         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
247             throw new BabelServiceClientException(sanitizedJson);
248         }
249
250         return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());
251     }
252 }