Add encryption for passwords
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / SdcReq.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                             reserved.
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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.client.req;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.core.JsonParseException;
29 import com.fasterxml.jackson.databind.JsonMappingException;
30 import com.fasterxml.jackson.databind.JsonNode;
31 import com.fasterxml.jackson.databind.ObjectMapper;
32 import com.fasterxml.jackson.databind.node.ArrayNode;
33 import com.fasterxml.jackson.databind.node.ObjectNode;
34
35 import java.io.IOException;
36 import java.nio.charset.StandardCharsets;
37 import java.security.GeneralSecurityException;
38 import java.util.ArrayList;
39 import java.util.Base64;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Map.Entry;
43
44 import org.apache.commons.codec.digest.DigestUtils;
45 import org.camunda.bpm.engine.delegate.DelegateExecution;
46 import org.onap.clamp.clds.client.SdcCatalogServices;
47 import org.onap.clamp.clds.model.CldsSdcResource;
48 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
49 import org.onap.clamp.clds.model.prop.Global;
50 import org.onap.clamp.clds.model.prop.ModelProperties;
51 import org.onap.clamp.clds.model.prop.Tca;
52 import org.onap.clamp.clds.model.refprop.RefProp;
53 import org.onap.clamp.clds.util.CryptoUtils;
54 import org.springframework.beans.factory.annotation.Autowired;
55
56 /**
57  * Construct a Sdc request given CLDS objects.
58  */
59 public class SdcReq {
60     @Autowired
61     protected CryptoUtils             cryptoUtils;
62     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(SdcReq.class);
63     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
64     @Autowired
65     protected RefProp                 refProp;
66
67     /**
68      * Format the Blueprint from a Yaml
69      *
70      * @param prop
71      *            The ModelProperties describing the clds model
72      * @param docText
73      *            The Yaml file that must be converted
74      *
75      * @return A String containing the BluePrint
76      * @throws JsonParseException
77      *             In case of issues
78      * @throws JsonMappingException
79      *             In case of issues
80      * @throws IOException
81      *             In case of issues
82      */
83     public String formatBlueprint(ModelProperties prop, String docText)
84             throws JsonParseException, JsonMappingException, IOException {
85         String yamlvalue = getYamlvalue(docText);
86         String updatedBlueprint = "";
87         Tca tca = prop.getType(Tca.class);
88         if (tca.isFound()) {
89             updatedBlueprint = TcaRequestFormatter.updatedBlueprintWithConfiguration(refProp, prop, yamlvalue);
90         }
91         logger.info("value of blueprint:" + updatedBlueprint);
92         return updatedBlueprint;
93     }
94
95     /**
96      * Format the SDC Locations Request in the JSON Format
97      *
98      * @param prop
99      *            The ModelProperties describing the clds model
100      * @param artifactName
101      *            The name of the artifact
102      *
103      * @return SDC Locations request in the JSON Format
104      */
105     public String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
106         ObjectMapper objectMapper = new ObjectMapper();
107         Global global = prop.getGlobal();
108         List<String> locationsList = global.getLocation();
109         ArrayNode locationsArrayNode = objectMapper.createArrayNode();
110         ObjectNode locationObject = objectMapper.createObjectNode();
111         for (String currLocation : locationsList) {
112             locationsArrayNode.add(currLocation);
113         }
114         locationObject.put("artifactName", artifactName);
115         locationObject.putPOJO("locations", locationsArrayNode);
116         String locationJsonFormat = locationObject.toString();
117         logger.info("Value of location Json Artifact:" + locationsArrayNode);
118         return locationJsonFormat;
119     }
120
121     /**
122      * Format the SDC Request
123      *
124      * @param payloadData
125      *            The ModelProperties describing the clds model
126      * @param artifactName
127      *            The name of the artifact
128      * @param artifactLabel
129      *            The Label of the artifact
130      * @param artifactType
131      *            The type of the artifact
132      * @return formatted SDC Request
133      * @throws IOException
134      *             In case of issues
135      */
136     public String formatSdcReq(String payloadData, String artifactName, String artifactLabel, String artifactType)
137             throws IOException {
138         logger.info("artifact=" + payloadData);
139         String base64Artifact = base64Encode(payloadData);
140         return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
141                 + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
142                 + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
143                 + "} \n";
144     }
145
146     /**
147      * Get the SDC Request URL
148      *
149      * @param prop
150      *            The ModelProperties describing the clds model
151      * @param url
152      *            url
153      * @return SDC Request URL
154      */
155     public String getSdcReqUrl(ModelProperties prop, String url) {
156         Global globalProps = prop.getGlobal();
157         String serviceUUID = "";
158         String resourceInstanceName = "";
159         if (globalProps != null) {
160             List<String> resourceVf = globalProps.getResourceVf();
161             if (resourceVf != null && !resourceVf.isEmpty()) {
162                 resourceInstanceName = resourceVf.get(0);
163             }
164             if (globalProps.getService() != null) {
165                 serviceUUID = globalProps.getService();
166             }
167         }
168         String normalizedResourceInstanceName = normalizeResourceInstanceName(resourceInstanceName);
169         return url + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
170     }
171
172     /**
173      * To get List of urls for all vfresources
174      *
175      * @param prop
176      * @param baseUrl
177      * @param sdcCatalogServices
178      * @param execution
179      * @return
180      * @throws GeneralSecurityException
181      */
182     public List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl, SdcCatalogServices sdcCatalogServices,
183             DelegateExecution execution) throws GeneralSecurityException {
184         // TODO : refact and regroup with very similar code
185         List<String> urlList = new ArrayList<>();
186         Global globalProps = prop.getGlobal();
187         if (globalProps != null) {
188             if (globalProps.getService() != null) {
189                 String serviceInvariantUUID = globalProps.getService();
190                 execution.setVariable("serviceInvariantUUID", serviceInvariantUUID);
191                 List<String> resourceVfList = globalProps.getResourceVf();
192                 String serviceUUID = sdcCatalogServices.getServiceUuidFromServiceInvariantId(serviceInvariantUUID);
193                 String sdcServicesInformation = sdcCatalogServices.getSdcServicesInformation(serviceUUID);
194                 CldsSdcServiceDetail cldsSdcServiceDetail = sdcCatalogServices
195                         .getCldsSdcServiceDetailFromJson(sdcServicesInformation);
196                 if (cldsSdcServiceDetail != null && resourceVfList != null) {
197                     List<CldsSdcResource> cldsSdcResourcesList = cldsSdcServiceDetail.getResources();
198                     if (cldsSdcResourcesList != null && !cldsSdcResourcesList.isEmpty()) {
199                         for (CldsSdcResource CldsSdcResource : cldsSdcResourcesList) {
200                             if (CldsSdcResource != null && CldsSdcResource.getResoucreType() != null
201                                     && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")
202                                     && resourceVfList.contains(CldsSdcResource.getResourceInvariantUUID())) {
203                                 String normalizedResourceInstanceName = normalizeResourceInstanceName(
204                                         CldsSdcResource.getResourceInstanceName());
205                                 String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
206                                         + normalizedResourceInstanceName + "/artifacts";
207                                 urlList.add(svcUrl);
208                             }
209                         }
210                     }
211                 }
212             }
213         }
214         return urlList;
215     }
216
217     /**
218      * "Normalize" the resource instance name: - Remove spaces, underscores,
219      * dashes, and periods. - make lower case This is required by SDC when using
220      * the resource instance name to upload an artifact.
221      *
222      * @param inText
223      * @return
224      */
225     public String normalizeResourceInstanceName(String inText) {
226         return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
227     }
228
229     /**
230      * from michael
231      *
232      * @param data
233      * @return
234      */
235     public String calculateMD5ByString(String data) {
236         String calculatedMd5 = DigestUtils.md5Hex(data);
237         // encode base-64 result
238         return base64Encode(calculatedMd5.getBytes());
239     }
240
241     /**
242      * Base 64 encode a String.
243      *
244      * @param inText
245      * @return
246      */
247     public String base64Encode(String inText) {
248         return base64Encode(stringToByteArray(inText));
249     }
250
251     /**
252      * Convert String to byte array.
253      *
254      * @param inText
255      * @return
256      */
257     public byte[] stringToByteArray(String inText) {
258         return inText.getBytes(StandardCharsets.UTF_8);
259     }
260
261     /**
262      * Base 64 encode a byte array.
263      *
264      * @param bytes
265      * @return
266      */
267     public String base64Encode(byte[] bytes) {
268         Base64.Encoder encoder = Base64.getEncoder();
269         return encoder.encodeToString(bytes);
270     }
271
272     /**
273      * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
274      * dGVzdDoxMjM0NTY=).
275      *
276      * @return The String with Basic Auth and password
277      * @throws GeneralSecurityException
278      *             In case of issue when decryting the SDC password
279      */
280     public String getSdcBasicAuth() throws GeneralSecurityException {
281         String sdcId = refProp.getStringValue("sdc.serviceUsername");
282         String sdcPw = refProp.getStringValue("sdc.servicePassword");
283         String password = cryptoUtils.decrypt(sdcPw);
284         String idPw = base64Encode(sdcId + ":" + password);
285         return "Basic " + idPw;
286     }
287
288     /**
289      * Method to get yaml/template properties value from json
290      *
291      * @param docText
292      * @return
293      * @throws IOException
294      */
295     public String getYamlvalue(String docText) throws IOException {
296         ObjectMapper objectMapper = new ObjectMapper();
297         String yamlFileValue = "";
298         ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);
299         Iterator<Entry<String, JsonNode>> entryItr = root.fields();
300         while (entryItr.hasNext()) {
301             Entry<String, JsonNode> entry = entryItr.next();
302             String key = entry.getKey();
303             if (key != null && key.equalsIgnoreCase("global")) {
304                 ArrayNode arrayNode = (ArrayNode) entry.getValue();
305                 for (JsonNode anArrayNode : arrayNode) {
306                     ObjectNode node = (ObjectNode) anArrayNode;
307                     ArrayNode arrayValueNode = (ArrayNode) node.get("value");
308                     JsonNode jsonNode = arrayValueNode.get(0);
309                     yamlFileValue = jsonNode.asText();
310                     logger.info("value:" + yamlFileValue);
311                 }
312                 break;
313             }
314         }
315         return yamlFileValue;
316     }
317 }