Fix weak-cryptography issues
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / vendor-software-products-rest / vnf-repository-rest-services / src / main / java / org / openecomp / sdcrests / vsp / rest / services / VnfPackageRepositoryImpl.java
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
3  * Modifications Copyright 2018 European Support Limited
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 package org.openecomp.sdcrests.vsp.rest.services;
18
19 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
20 import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
21 import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;
22
23 import java.io.IOException;
24 import java.nio.ByteBuffer;
25 import java.nio.charset.StandardCharsets;
26 import java.security.GeneralSecurityException;
27 import java.security.KeyManagementException;
28 import java.security.NoSuchAlgorithmException;
29 import java.util.List;
30 import java.util.Objects;
31 import java.util.Optional;
32 import javax.inject.Named;
33 import javax.net.ssl.SSLContext;
34 import javax.ws.rs.client.Client;
35 import javax.ws.rs.client.ClientBuilder;
36 import javax.ws.rs.core.Response;
37 import org.onap.config.api.ConfigurationManager;
38 import org.onap.config.api.JettySSLUtils;
39 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
40 import org.openecomp.sdc.common.errors.CoreException;
41 import org.openecomp.sdc.common.errors.ErrorCode;
42 import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
43 import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
44 import org.openecomp.sdc.logging.api.Logger;
45 import org.openecomp.sdc.logging.api.LoggerFactory;
46 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
47 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
49 import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo;
50 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
51 import org.openecomp.sdc.versioning.VersioningManager;
52 import org.openecomp.sdc.versioning.VersioningManagerFactory;
53 import org.openecomp.sdc.versioning.dao.types.Version;
54 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
55 import org.openecomp.sdcrests.vsp.rest.VnfPackageRepository;
56 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
57 import org.springframework.context.annotation.Scope;
58 import org.springframework.stereotype.Service;
59
60 /**
61  * Enables integration API interface with VNF Repository (VNFSDK).
62  * <ol>
63  *     <li>Get all the VNF Package Meta-data.</li>
64  *     <li>Download a VNF Package.</li>
65  *     <li>Import a VNF package to SDC catalog (Download & validate).</li>
66  * </ol>
67  *
68  * @version Amsterdam release (ONAP 1.0)
69  */
70 @Named
71 @Service("vnfPackageRepository")
72 @Scope(value = "prototype")
73 public class VnfPackageRepositoryImpl implements VnfPackageRepository {
74
75     private static final Logger LOGGER = LoggerFactory.getLogger(VnfPackageRepositoryImpl.class);
76     private static final Client CLIENT = trustSSLClient();
77
78     private static Client trustSSLClient() {
79         try {
80             SSLContext sslcontext = JettySSLUtils.getSslContext();
81             return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((requestedHost, remoteServerSession)
82                     -> requestedHost.equalsIgnoreCase(remoteServerSession.getPeerHost())).build();
83
84         } catch (IOException | GeneralSecurityException e) {
85             LOGGER.error("Failed to initialize SSL context", e);
86         }
87         return ClientBuilder.newClient();
88     }
89
90
91     private final Configuration config;
92
93     public VnfPackageRepositoryImpl(Configuration config) {
94         this.config = config;
95     }
96
97     public VnfPackageRepositoryImpl() {
98         this(new FileConfiguration());
99     }
100
101     @Override
102     public Response getVnfPackages(String vspId, String versionId, String user) {
103         LOGGER.debug("Get VNF Packages from Repository: {}", vspId);
104         final String getVnfPackageUri = config.getGetUri();
105         Response remoteResponse = CLIENT.target(getVnfPackageUri).request().get();
106         if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
107             return handleUnexpectedStatus("querying VNF package metadata", getVnfPackageUri, remoteResponse);
108         }
109         LOGGER.debug("Response from VNF Repository: {}", remoteResponse);
110         return Response.ok(remoteResponse.readEntity(String.class)).build();
111     }
112
113     @Override
114     public Response importVnfPackage(String vspId, String versionId, String csarId, String user) {
115         LOGGER.debug("Import VNF Packages from Repository: {}", csarId);
116         final String downloadPackageUri = String.format(config.getDownloadUri(), csarId);
117         Response remoteResponse = CLIENT.target(downloadPackageUri).request().get();
118         if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
119             return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse);
120         }
121         LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri);
122         byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1);
123         return uploadVnfPackage(vspId, versionId, csarId, payload);
124     }
125
126     private Response uploadVnfPackage(final String vspId, final String versionId, final String csarId, final byte[] payload) {
127         try {
128             final OrchestrationTemplateCandidateManager candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance()
129                 .createInterface();
130             final String filename = formatFilename(csarId);
131             final String fileExtension = getFileExtension(filename);
132             final OnboardPackageInfo onboardPackageInfo = new OnboardPackageInfo(getNetworkPackageName(filename), fileExtension,
133                 ByteBuffer.wrap(payload), OnboardingTypesEnum.getOnboardingTypesEnum(fileExtension));
134             final VspDetails vspDetails = new VspDetails(vspId, getVersion(vspId, versionId));
135             final UploadFileResponse response = candidateManager.upload(vspDetails, onboardPackageInfo);
136             final UploadFileResponseDto uploadFileResponse = new MapUploadFileResponseToUploadFileResponseDto()
137                 .applyMapping(response, UploadFileResponseDto.class);
138             return Response.ok(uploadFileResponse).build();
139         } catch (final Exception e) {
140             ErrorCode error = new GeneralErrorBuilder().build();
141             LOGGER.error("Exception while uploading package received from VNF Repository", new CoreException(error, e));
142             return generateInternalServerError(error);
143         }
144     }
145
146     @Override
147     public Response downloadVnfPackage(String vspId, String versionId, String csarId, String user) {
148         LOGGER.debug("Download VNF package from repository: csarId={}", csarId);
149         final String downloadPackageUri = String.format(config.getDownloadUri(), csarId);
150         Response remoteResponse = CLIENT.target(downloadPackageUri).request().get();
151         if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
152             return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse);
153         }
154         byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1);
155         Response.ResponseBuilder response = Response.ok(payload);
156         response.header(CONTENT_DISPOSITION, "attachment; filename=" + formatFilename(csarId));
157         LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri);
158         return response.build();
159     }
160
161     private Version getVersion(String vspId, String versionId) {
162         VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface();
163         return findVersion(versioningManager.list(vspId), versionId).orElse(new Version(versionId));
164     }
165
166     Optional<Version> findVersion(List<Version> versions, String requestedVersion) {
167         return versions.stream().filter(ver -> Objects.equals(ver.getId(), requestedVersion)).findAny();
168     }
169
170     private static Response handleUnexpectedStatus(String action, String uri, Response response) {
171         ErrorCode error = new GeneralErrorBuilder().build();
172         if (LOGGER.isErrorEnabled()) {
173             String body = response.hasEntity() ? response.readEntity(String.class) : "";
174             LOGGER.error("Unexpected response status while {}: URI={}, status={}, body={}", action, uri, response.getStatus(), body,
175                 new CoreException(error));
176         }
177         return generateInternalServerError(error);
178     }
179
180     private static Response generateInternalServerError(ErrorCode error) {
181         ErrorCodeAndMessage payload = new ErrorCodeAndMessage(Response.Status.INTERNAL_SERVER_ERROR, error);
182         return Response.serverError().entity(payload).build();
183     }
184
185     private static String formatFilename(String csarId) {
186         return "temp_" + csarId + ".csar";
187     }
188
189     interface Configuration {
190
191         String getGetUri();
192
193         String getDownloadUri();
194     }
195
196     static class FileConfiguration implements Configuration {
197
198         @Override
199         public String getGetUri() {
200             return LazyFileConfiguration.INSTANCE.getGetUri();
201         }
202
203         @Override
204         public String getDownloadUri() {
205             return LazyFileConfiguration.INSTANCE.getDownloadUri();
206         }
207
208         private static class LazyFileConfiguration implements Configuration {
209
210             private static final String CONFIG_NAMESPACE = "vnfrepo";
211             private static final String DEFAULT_HOST = "localhost";
212             private static final String DEFAULT_PORT = "8702";
213             private static final String DEFAULT_URI_PREFIX = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars";
214             private static final String DEFAULT_LIST_URI = DEFAULT_URI_PREFIX + "/";
215             private static final String DEFAULT_DOWNLOAD_URI = DEFAULT_URI_PREFIX + "/%s/files";
216             private static final LazyFileConfiguration INSTANCE = new LazyFileConfiguration();
217             private final String getUri;
218             private final String downloadUri;
219
220             private LazyFileConfiguration() {
221                 org.onap.config.api.Configuration config = ConfigurationManager.lookup();
222                 String host = readConfig(config, "vnfRepoHost", DEFAULT_HOST);
223                 String port = readConfig(config, "vnfRepoPort", DEFAULT_PORT);
224                 String listPackagesUri = readConfig(config, "getVnfUri", DEFAULT_LIST_URI);
225                 String downloadPackageUri = readConfig(config, "downloadVnfUri", DEFAULT_DOWNLOAD_URI);
226                 this.getUri = formatUri(host, port, listPackagesUri);
227                 this.downloadUri = formatUri(host, port, downloadPackageUri);
228             }
229
230             private String readConfig(org.onap.config.api.Configuration config, String key, String defaultValue) {
231                 try {
232                     String value = config.getAsString(CONFIG_NAMESPACE, key);
233                     return (value == null) ? defaultValue : value;
234                 } catch (Exception e) {
235                     LOGGER.error("Failed to read VNF repository configuration key '{}', default value '{}' will be used", key, defaultValue, e);
236                     return defaultValue;
237                 }
238             }
239
240             private static String formatUri(String host, String port, String path) {
241                 return "https://" + host + ":" + port + (path.startsWith("/") ? path : "/" + path);
242             }
243
244             public String getGetUri() {
245                 return getUri;
246             }
247
248             public String getDownloadUri() {
249                 return downloadUri;
250             }
251         }
252     }
253 }