fix CRITICAL xxe (XML External Entity) issues identified in sonarcloud
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / entity / model / ModelArtifact.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.entity.model;
22
23 import java.io.StringWriter;
24 import java.util.List;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27 import javax.xml.XMLConstants;
28 import javax.xml.transform.OutputKeys;
29 import javax.xml.transform.Transformer;
30 import javax.xml.transform.TransformerException;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.dom.DOMSource;
33 import javax.xml.transform.stream.StreamResult;
34 import org.onap.aai.modelloader.config.ModelLoaderConfig;
35 import org.onap.aai.modelloader.entity.Artifact;
36 import org.onap.aai.modelloader.entity.ArtifactType;
37 import org.onap.aai.modelloader.restclient.AaiRestClient;
38 import org.onap.aai.restclient.client.OperationResult;
39 import org.w3c.dom.Node;
40
41
42 public class ModelArtifact extends AbstractModelArtifact {
43
44     private static final String AAI_MODEL_VER_SUB_URL = "/model-vers/model-ver";
45
46     private static final String FAILURE_MSG_PREFIX = "Ingestion failed for ";
47     private static final String ROLLBACK_MSG_SUFFIX = ". Rolling back distribution.";
48
49
50     private String modelVerId;
51     private String modelInvariantId;
52     private Node modelVer;
53     private boolean firstVersionOfModel = false;
54
55     public ModelArtifact() {
56         super(ArtifactType.MODEL);
57     }
58
59     public String getModelVerId() {
60         return modelVerId;
61     }
62
63     public void setModelVerId(String modelVerId) {
64         this.modelVerId = modelVerId;
65     }
66
67     public String getModelInvariantId() {
68         return modelInvariantId;
69     }
70
71     public void setModelInvariantId(String modelInvariantId) {
72         this.modelInvariantId = modelInvariantId;
73     }
74
75     public Node getModelVer() {
76         return modelVer;
77     }
78
79     public void setModelVer(Node modelVer) {
80         this.modelVer = modelVer;
81     }
82
83     @Override
84     public String getUniqueIdentifier() {
85         return getModelInvariantId() + "|" + getModelVerId();
86     }
87
88
89     /**
90      * Test whether the specified resource (URL) can be requested successfully
91      *
92      * @param aaiClient
93      * @param distId
94      * @param xmlResourceUrl
95      * @return true if a request to GET this resource as XML media is successful (status OK)
96      */
97     private boolean xmlResourceCanBeFetched(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
98         OperationResult getResponse = getResourceModel(aaiClient, distId, xmlResourceUrl);
99         return getResponse != null && getResponse.getResultCode() == Response.Status.OK.getStatusCode();
100     }
101
102     /**
103      * Test whether the specified resource (URL) can be requested successfully
104      *
105      * @param aaiClient
106      * @param distId
107      * @param xmlResourceUrl
108      * @return OperationResult the result of the operation
109      */
110     private OperationResult getResourceModel(AaiRestClient aaiClient, String distId, String xmlResourceUrl) {
111         return aaiClient.getResource(xmlResourceUrl, distId, MediaType.APPLICATION_XML_TYPE);
112     }
113
114     /**
115      * PUT the specified XML resource
116      *
117      * @param aaiClient
118      * @param distId
119      * @param resourceUrl
120      * @param payload
121      * @return true if the resource PUT as XML media was successful (status OK)
122      */
123     private boolean putXmlResource(AaiRestClient aaiClient, String distId, String resourceUrl, String payload) {
124         OperationResult putResponse =
125                 aaiClient.putResource(resourceUrl, payload, distId, MediaType.APPLICATION_XML_TYPE);
126         return putResponse != null && putResponse.getResultCode() == Response.Status.CREATED.getStatusCode();
127     }
128
129     @Override
130     public boolean push(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
131             List<Artifact> completedArtifacts) {
132         if (config.useGizmo()) {
133             return pushToGizmo(aaiClient, config, distId);
134         }
135
136         return pushToResources(aaiClient, config, distId, completedArtifacts);
137     }
138
139     private boolean pushToResources(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
140             List<Artifact> completedArtifacts) {
141         boolean success = false;
142
143         // See whether the model is already present
144         String resourceUrl = getModelUrl(config);
145         OperationResult result = getResourceModel(aaiClient, distId, resourceUrl);
146
147         if (result != null) {
148             if (result.getResultCode() == Response.Status.OK.getStatusCode()) {
149                 success = updateExistingModel(aaiClient, config, distId, completedArtifacts);
150             } else if (result.getResultCode() == Response.Status.NOT_FOUND.getStatusCode()) {
151                 success = createNewModel(aaiClient, distId, completedArtifacts, resourceUrl);
152             } else {
153                 logModelUpdateFailure(
154                         "Response code " + result.getResultCode() + " invalid for getting resource model");
155             }
156         } else {
157             logModelUpdateFailure("Null response from RestClient");
158         }
159
160         return success;
161     }
162
163     private boolean createNewModel(AaiRestClient aaiClient, String distId, List<Artifact> completedArtifacts,
164             String resourceUrl) {
165         boolean success;
166         // Assume that the model does not exist and attempt the PUT
167         success = putXmlResource(aaiClient, distId, resourceUrl, getPayload());
168         if (success) {
169             completedArtifacts.add(this);
170
171             // Record state to remember that this is the first version of the model (just added).
172             firstVersionOfModel = true;
173
174             logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested.");
175         } else {
176             logModelUpdateFailure("Error creating model. Skipping ingestion.");
177         }
178         return success;
179     }
180
181     private void logModelUpdateFailure(String message) {
182         logErrorMsg(FAILURE_MSG_PREFIX + getType() + " " + getUniqueIdentifier() + " " + message + ROLLBACK_MSG_SUFFIX);
183     }
184
185     private boolean updateExistingModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
186             List<Artifact> completedArtifacts) {
187         boolean success;
188         logInfoMsg(getType() + " " + getModelInvariantId() + " already exists.  Skipping ingestion.");
189         success = pushModelVersion(aaiClient, config, distId, completedArtifacts);
190         return success;
191     }
192
193     /**
194      * @param aaiClient
195      * @param config
196      * @param distId
197      * @param completedArtifacts
198      * @return
199      */
200     private boolean pushModelVersion(AaiRestClient aaiClient, ModelLoaderConfig config, String distId,
201             List<Artifact> completedArtifacts) {
202         if (xmlResourceCanBeFetched(aaiClient, distId, getModelVerUrl(config))) {
203             logInfoMsg(getType() + " " + getUniqueIdentifier() + " already exists.  Skipping ingestion.");
204             return true;
205         }
206
207         // Load the model version
208         boolean success = true;
209         try {
210             success = putXmlResource(aaiClient, distId, getModelVerUrl(config), nodeToString(getModelVer()));
211             if (success) {
212                 completedArtifacts.add(this);
213                 logInfoMsg(getType() + " " + getUniqueIdentifier() + " successfully ingested.");
214             } else {
215                 logModelUpdateFailure("Error pushing model");
216             }
217         } catch (TransformerException e) {
218             logModelUpdateFailure(e.getMessage());
219             success = false;
220         }
221
222         return success;
223     }
224
225
226     @Override
227     public void rollbackModel(AaiRestClient aaiClient, ModelLoaderConfig config, String distId) {
228         // Gizmo is resilient and doesn't require a rollback. A redistribution will work fine even if
229         // the model is partially loaded.
230         if (config.useGizmo()) {
231             return;
232         }
233
234         String url = getModelVerUrl(config);
235         if (firstVersionOfModel) {
236             // If this was the first version of the model which was added, we want to remove the entire
237             // model rather than just the version.
238             url = getModelUrl(config);
239         }
240
241         // Best effort to delete. Nothing we can do in the event this fails.
242         aaiClient.getAndDeleteResource(url, distId);
243     }
244
245     private String getModelUrl(ModelLoaderConfig config) {
246         String baseURL = config.getAaiBaseUrl().trim();
247         String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim();
248         String instance = getModelInvariantId();
249
250         if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
251             baseURL = baseURL + "/";
252         }
253
254         if (baseURL.endsWith("/") && subURL.startsWith("/")) {
255             baseURL = baseURL.substring(0, baseURL.length() - 1);
256         }
257
258         if (!subURL.endsWith("/")) {
259             subURL = subURL + "/";
260         }
261
262         return baseURL + subURL + instance;
263     }
264
265     private String getModelVerUrl(ModelLoaderConfig config) {
266         String baseURL = config.getAaiBaseUrl().trim();
267         String subURL = config.getAaiModelUrl(getModelNamespaceVersion()).trim() + getModelInvariantId()
268                 + AAI_MODEL_VER_SUB_URL;
269         String instance = getModelVerId();
270
271         if (!baseURL.endsWith("/") && !subURL.startsWith("/")) {
272             baseURL = baseURL + "/";
273         }
274
275         if (baseURL.endsWith("/") && subURL.startsWith("/")) {
276             baseURL = baseURL.substring(0, baseURL.length() - 1);
277         }
278
279         if (!subURL.endsWith("/")) {
280             subURL = subURL + "/";
281         }
282
283         return baseURL + subURL + instance;
284     }
285
286     private String nodeToString(Node node) throws TransformerException {
287         StringWriter sw = new StringWriter();
288         TransformerFactory transFact = TransformerFactory.newInstance();
289         transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
290         transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
291         Transformer t = transFact.newTransformer();
292         t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
293         t.transform(new DOMSource(node), new StreamResult(sw));
294         return sw.toString();
295     }
296 }