Refactor for Sonar smells and code coverage
[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-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 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 package org.onap.aai.modelloader.restclient;
22
23 import com.google.gson.Gson;
24 import com.google.gson.reflect.TypeToken;
25 import com.google.json.JsonSanitizer;
26 import com.sun.jersey.api.client.Client; // NOSONAR
27 import com.sun.jersey.api.client.ClientResponse;
28 import com.sun.jersey.api.client.WebResource;
29 import com.sun.jersey.api.client.config.DefaultClientConfig;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
34 import java.security.KeyManagementException;
35 import java.security.KeyStore;
36 import java.security.KeyStoreException;
37 import java.security.NoSuchAlgorithmException;
38 import java.security.UnrecoverableKeyException;
39 import java.security.cert.CertificateException;
40 import java.security.cert.X509Certificate;
41 import java.util.Base64;
42 import java.util.Collections;
43 import java.util.List;
44 import java.util.Objects;
45 import javax.net.ssl.HttpsURLConnection;
46 import javax.net.ssl.KeyManagerFactory;
47 import javax.net.ssl.SSLContext;
48 import javax.net.ssl.TrustManager;
49 import javax.net.ssl.TrustManagerFactory;
50 import javax.net.ssl.X509TrustManager;
51 import javax.ws.rs.core.Response;
52 import org.json.JSONException;
53 import org.json.JSONObject;
54 import org.onap.aai.babel.service.data.BabelArtifact;
55 import org.onap.aai.cl.api.Logger;
56 import org.onap.aai.cl.eelf.LoggerFactory;
57 import org.onap.aai.modelloader.config.ModelLoaderConfig;
58 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
59
60 /**
61  * HTTPS Client for interfacing with Babel.
62  *
63  */
64 public class HttpsBabelServiceClient implements BabelServiceClient {
65
66     private static final Logger logger = LoggerFactory.getInstance().getLogger(HttpsBabelServiceClient.class);
67
68     private static final String SSL_PROTOCOL = "TLS";
69     private static final String KEYSTORE_ALGORITHM = "SunX509";
70     private static final String KEYSTORE_TYPE = "PKCS12";
71
72     private final ModelLoaderConfig config;
73     private final Client client;
74
75     /**
76      * @param config
77      * @throws NoSuchAlgorithmException
78      * @throws KeyStoreException
79      * @throws CertificateException
80      * @throws IOException
81      * @throws UnrecoverableKeyException
82      * @throws KeyManagementException
83      * @throws BabelServiceClientException
84      */
85     public HttpsBabelServiceClient(ModelLoaderConfig config)
86             throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
87             UnrecoverableKeyException, KeyManagementException, BabelServiceClientException {
88         this.config = config;
89
90         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client");
91
92         SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
93         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
94         KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
95
96         String clientCertPassword = config.getBabelKeyStorePassword();
97
98         char[] pwd = null;
99         if (clientCertPassword != null) {
100             pwd = clientCertPassword.toCharArray();
101         }
102
103         TrustManager[] trustManagers = getTrustManagers();
104
105         String clientCertFileName = config.getBabelKeyStorePath();
106         if (clientCertFileName == null) {
107             ctx.init(null, trustManagers, null);
108         } else {
109             InputStream fin = Files.newInputStream(Paths.get(clientCertFileName));
110             keyStore.load(fin, pwd);
111             kmf.init(keyStore, pwd);
112             ctx.init(kmf.getKeyManagers(), trustManagers, null);
113         }
114
115         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
116
117         HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
118         HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
119
120         client = Client.create(new DefaultClientConfig());
121
122         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
123     }
124
125     private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
126             IOException, BabelServiceClientException {
127         TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
128         // Using null here initializes the TMF with the default trust store.
129         tmf.init((KeyStore) null);
130
131         // Create a new Trust Manager from the local trust store.
132         String trustStoreFile = config.getBabelTrustStorePath();
133         if (trustStoreFile == null) {
134             throw new BabelServiceClientException("No Babel trust store defined");
135         }
136         try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) {
137             KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
138             myTrustStore.load(myKeys, config.getBabelTrustStorePassword().toCharArray());
139             tmf.init(myTrustStore);
140         }
141         X509TrustManager localTm = findX509TrustManager(tmf);
142
143         // Create a custom trust manager that wraps both our trust store and the default.
144         final X509TrustManager finalLocalTm = localTm;
145
146         // Find the default trust manager.
147         final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
148
149         return new TrustManager[] {new X509TrustManager() {
150             @Override
151             public X509Certificate[] getAcceptedIssuers() {
152                 return defaultTrustManager.getAcceptedIssuers();
153             }
154
155             @Override
156             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
157                 try {
158                     finalLocalTm.checkServerTrusted(chain, authType);
159                 } catch (CertificateException e) {
160                     defaultTrustManager.checkServerTrusted(chain, authType);
161                 }
162             }
163
164             @Override
165             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
166                 defaultTrustManager.checkClientTrusted(chain, authType);
167             }
168         }};
169     }
170
171     private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
172         X509TrustManager trustManager = null;
173         for (TrustManager tm : tmf.getTrustManagers()) {
174             if (tm instanceof X509TrustManager) {
175                 trustManager = (X509TrustManager) tm;
176                 break;
177             }
178         }
179         return trustManager;
180     }
181
182     /**
183      * @param artifactPayload
184      * @param artifactName
185      * @param artifactVersion
186      * @param transactionId
187      * @return
188      * @throws BabelServiceClientException
189      * @throws JSONException
190      */
191     @Override
192     public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
193             String transactionId) throws BabelServiceClientException {
194         Objects.requireNonNull(artifactPayload);
195
196         String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
197
198         JSONObject obj = new JSONObject();
199         try {
200             obj.put("csar", encodedPayload);
201             obj.put("artifactVersion", artifactVersion);
202             obj.put("artifactName", artifactName);
203         } catch (JSONException ex) {
204             throw new BabelServiceClientException(ex);
205         }
206
207         if (logger.isInfoEnabled()) {
208             logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
209                     + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
210         }
211
212         WebResource webResource = client.resource(config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl());
213         ClientResponse response = webResource.type("application/json")
214                 .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
215                 .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
216                 .post(ClientResponse.class, obj.toString());
217         String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
218
219         if (logger.isDebugEnabled()) {
220             logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
221                     "Babel response " + response.getStatus() + " " + sanitizedJson);
222         }
223
224         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
225             throw new BabelServiceClientException(sanitizedJson);
226         }
227
228         return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());
229     }
230 }