2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.StringReader;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
30 import java.util.Optional;
31 import java.util.Properties;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import java.util.stream.Collectors;
36 import org.apache.commons.lang3.tuple.ImmutablePair;
37 import org.openecomp.sdc.be.config.BeEcompErrorManager;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
39 import org.openecomp.sdc.be.dao.api.ActionStatus;
40 import org.openecomp.sdc.be.impl.ComponentsUtils;
41 import org.openecomp.sdc.be.tosca.CsarUtils;
42 import org.openecomp.sdc.common.util.GeneralUtility;
43 import org.openecomp.sdc.exception.ResponseFormat;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 import fj.data.Either;
49 public class CsarValidationUtils {
51 private static final Logger log = LoggerFactory.getLogger(CsarValidationUtils.class);
53 private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version";
55 private static final String CSAR_VERSION = "CSAR-Version";
57 private static final String CREATED_BY = "Created-By";
59 private static final String NEW_LINE_DELM = "\n";
61 public final static String TOSCA_METADATA = "TOSCA-Metadata";
62 public final static String TOSCA_FILE = "TOSCA.meta";
63 public final static String DEL_PATTERN = "([/\\\\]+)";
64 public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA +
65 // Artifact Group (i.e Deployment/Informational)
66 DEL_PATTERN + TOSCA_FILE;
68 public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
70 private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS };
72 public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta";
74 public static final String TOSCA_CSAR_EXTENSION = ".csar";
79 * @param componentsUtils
82 public static Either<Boolean, ResponseFormat> validateCsar(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
83 Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
84 if (validateStatus.isRight()) {
85 return Either.right(validateStatus.right().value());
88 removeNonUniqueArtifactsFromCsar(csar);
90 log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID);
91 validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils);
92 if (validateStatus.isRight()) {
93 return Either.right(validateStatus.right().value());
95 return Either.left(true);
98 private static void removeNonUniqueArtifactsFromCsar(Map<String, byte[]> csar) {
100 List<String> nonUniqueArtifactsToRemove = new ArrayList<>();
101 String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]);
102 int numberOfArtifacts = paths.length;
103 for(int i = 0; i < numberOfArtifacts; ++i ){
104 collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove);
106 nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path));
109 private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
111 String[] parsedPath = paths[currInd].split("/");
112 String[] otherParsedPath;
113 int artifactNameInd = parsedPath.length - 1;
114 for(int j = currInd + 1; j < numberOfArtifacts; ++j ){
115 otherParsedPath = paths[j].split("/");
116 if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){
117 log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ",
118 parsedPath[artifactNameInd], paths[currInd], paths[j]);
119 nonUniqueArtifactsToRemove.add(paths[j]);
124 private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) {
125 boolean isEqualArtifactNames = false;
126 int artifactNameInd = parsedPath.length - 1;
127 int artifactGroupTypeInd = parsedPath.length - 3;
128 String groupType = parsedPath[artifactGroupTypeInd];
129 String artifactName = parsedPath[artifactNameInd];
130 String otherGroupType = otherParsedPath[artifactGroupTypeInd];
131 String otherArtifactName = otherParsedPath[artifactNameInd];
132 String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null;
134 if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){
135 isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]);
137 return isEqualArtifactNames;
140 public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
141 Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
142 if (validateStatus.isRight()) {
143 return Either.right(validateStatus.right().value());
145 Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
146 Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
147 if(!keyOp.isPresent()){
148 log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
149 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
150 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
152 byte[] toscaMetaBytes = csar.get(keyOp.get());
153 Properties props = new Properties();
155 String propStr = new String(toscaMetaBytes);
156 props.load(new StringReader(propStr.replace("\\","\\\\")));
157 } catch (IOException e) {
158 log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
159 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
160 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
163 String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS);
164 String[] ops = yamlFileName.split(DEL_PATTERN);
165 List<String> list = Arrays.asList(ops);
166 String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN));
167 keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny();
168 if(!keyOp.isPresent()){
169 log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
170 BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
171 return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
174 log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID);
175 byte[] yamlFileBytes = csar.get(yamlFileName);
176 if (yamlFileBytes == null) {
177 log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID);
178 BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + yamlFileName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
179 return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
182 String yamlFileContents = new String(yamlFileBytes);
184 return Either.left(new ImmutablePair<String, String>(yamlFileName, yamlFileContents));
187 public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
189 if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) {
190 log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
191 BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
192 return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE));
195 log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID);
196 byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE);
197 if (artifactsMetaBytes == null) {
198 log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID);
199 BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
200 return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
203 String artifactsFileContents = new String(artifactsMetaBytes);
205 return Either.left(new ImmutablePair<String, String>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents));
208 public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) {
209 if (!csar.containsKey(artifactPath)) {
210 log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID);
211 BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
212 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
215 log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID);
216 byte[] artifactFileBytes = csar.get(artifactPath);
217 if (artifactFileBytes == null) {
218 log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID);
219 BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
220 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID));
223 return Either.left(new ImmutablePair<String, byte[]>(artifactName, artifactFileBytes));
226 private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
228 Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
229 Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
230 if(!keyOp.isPresent()){
231 log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
232 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
233 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
236 byte[] toscaMetaBytes = csar.get(keyOp.get());
237 String toscaMetadata = new String(toscaMetaBytes);
238 String[] splited = toscaMetadata.split(NEW_LINE_DELM);
239 if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) {
240 log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
241 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
242 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
245 Either<Boolean, ResponseFormat> block_0Status = validateBlock_0(csarUUID, splited, componentsUtils);
246 if (block_0Status.isRight()) {
247 return Either.right(block_0Status.right().value());
250 return Either.left(true);
254 private static Either<Boolean, ResponseFormat> validateBlock_0(String csarUUID, String[] splited, ComponentsUtils componentsUtils) {
256 for (String toscaField : TOSCA_METADATA_FIELDS) {
258 Properties props = new Properties();
261 props.load(new ByteArrayInputStream(splited[index].getBytes()));
262 } catch (IOException e) {
263 log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
264 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
265 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
267 if (!props.containsKey(toscaField)) {
268 log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID);
269 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
270 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
272 String value = props.getProperty(toscaField);
273 if (value == null || value.isEmpty()) {
274 log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
275 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
276 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
279 // TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format
281 if (toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) {
282 if (!validateTOSCAMetaProperty(value)) {
283 log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID);
284 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
285 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
290 return Either.left(true);
293 private static boolean validateTOSCAMetaProperty(String toscaProperty) {
294 final String FLOAT_STRING = "^\\d{1}[.]\\d{1}$";
295 final Pattern FLOAT_PATTERN = Pattern.compile(FLOAT_STRING);
297 Matcher floatMatcher = FLOAT_PATTERN.matcher(toscaProperty);
298 return floatMatcher.matches();
301 private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
302 if (csar == null || csar.isEmpty()) {
303 log.debug("Error when fetching csar with ID {}", csarUUID);
304 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
305 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID);
306 return Either.right(responseFormat);
309 Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
310 Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
311 if(!keyOp.isPresent()){
313 log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID);
314 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
315 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
317 byte[] toscaMetaBytes = csar.get(keyOp.get());
318 // && exchanged for ||
319 if (toscaMetaBytes == null || toscaMetaBytes.length == 0) {
320 log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID);
321 BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
322 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
325 return Either.left(Boolean.TRUE);
328 public static Either<String, ResponseFormat> getToscaYamlChecksum(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
330 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils);
331 if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) {
332 log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID);
333 return Either.right(toscaYamlRes.right().value());
336 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes());
337 return Either.left(newCheckSum);
341 public static boolean isCsarPayloadName(String payloadName) {
342 if (payloadName == null)
344 return payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION);