2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.aai.modelloader.restclient;
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;
68 * HTTPS Client for interfacing with Babel.
71 public class HttpsBabelServiceClient implements BabelServiceClient {
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");
78 private static final String SSL_PROTOCOL = "TLS";
79 private static final String KEYSTORE_ALGORITHM = "SunX509";
80 private static final String KEYSTORE_TYPE = "PKCS12";
82 private final ModelLoaderConfig config;
83 private final Client client;
87 * @throws NoSuchAlgorithmException
88 * @throws KeyStoreException
89 * @throws CertificateException
91 * @throws UnrecoverableKeyException
92 * @throws KeyManagementException
93 * @throws BabelServiceClientException
95 public HttpsBabelServiceClient(ModelLoaderConfig config)
96 throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
97 UnrecoverableKeyException, KeyManagementException, BabelServiceClientException {
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);
107 String clientCertPassword = config.getBabelKeyStorePassword();
110 if (clientCertPassword != null) {
111 pwd = clientCertPassword.toCharArray();
114 TrustManager[] trustManagers = getTrustManagers();
116 String clientCertFileName = config.getBabelKeyStorePath();
117 if (clientCertFileName == null) {
118 ctx.init(null, trustManagers, null);
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);
126 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
128 HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
129 HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
132 client = Client.create(new DefaultClientConfig());
134 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
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);
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");
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);
153 X509TrustManager localTm = findX509TrustManager(tmf);
155 // Create a custom trust manager that wraps both our trust store and the default.
156 final X509TrustManager finalLocalTm = localTm;
158 // Find the default trust manager.
159 final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
161 return new TrustManager[] {new X509TrustManager() {
163 public X509Certificate[] getAcceptedIssuers() {
164 return defaultTrustManager.getAcceptedIssuers();
168 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
170 finalLocalTm.checkServerTrusted(chain, authType);
171 } catch (CertificateException e) { // NOSONAR
172 defaultTrustManager.checkServerTrusted(chain, authType);
177 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
178 defaultTrustManager.checkClientTrusted(chain, authType);
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;
195 * @param artifactPayload
196 * @param artifactName
197 * @param artifactVersion
198 * @param transactionId
200 * @throws BabelServiceClientException
201 * @throws JSONException
204 public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
205 String transactionId) throws BabelServiceClientException {
206 Objects.requireNonNull(artifactPayload);
208 String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
210 JSONObject obj = new JSONObject();
212 obj.put("csar", encodedPayload);
213 obj.put("artifactVersion", artifactVersion);
214 obj.put("artifactName", artifactName);
215 } catch (JSONException ex) {
216 throw new BabelServiceClientException(ex);
219 if (logger.isInfoEnabled()) {
220 logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
221 + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
224 MdcOverride override = new MdcOverride();
225 override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter));
227 WebResource webResource = client.resource(config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl());
228 ClientResponse response = webResource.type("application/json")
229 .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
230 .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
231 .post(ClientResponse.class, obj.toString());
232 String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
234 if (logger.isDebugEnabled()) {
235 logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
236 "Babel response " + response.getStatus() + " " + sanitizedJson);
239 metricsLogger.info(ModelLoaderMsgs.BABEL_REST_REQUEST, new LogFields() //
240 .setField(LogLine.DefinedFields.TARGET_ENTITY, "Babel")
241 .setField(LogLine.DefinedFields.STATUS_CODE,
242 Response.Status.fromStatusCode(response.getStatus()).getFamily()
243 .equals(Response.Status.Family.SUCCESSFUL) ? "COMPLETE" : "ERROR")
244 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
245 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusInfo().toString()), //
246 override, response.toString());
248 if (response.getStatus() != Response.Status.OK.getStatusCode()) {
249 throw new BabelServiceClientException(sanitizedJson);
252 return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());