Add fix for SQL injection.
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / AutoPushController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.controller;
22
23
24 import java.io.BufferedWriter;
25 import java.io.File;
26 import java.io.FileWriter;
27 import java.io.IOException;
28 import java.io.PrintWriter;
29 import java.net.URI;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40
41 import javax.script.SimpleBindings;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44
45 import org.json.JSONObject;
46 import org.onap.policy.common.logging.flexlogger.FlexLogger;
47 import org.onap.policy.common.logging.flexlogger.Logger;
48 import org.onap.policy.model.PDPGroupContainer;
49 import org.onap.policy.model.PDPPolicyContainer;
50 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.onap.policy.rest.jpa.PolicyEntity;
53 import org.onap.policy.rest.jpa.PolicyVersion;
54 import org.onap.policy.xacml.api.XACMLErrorConstants;
55 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
56 import org.onap.policy.xacml.std.pap.StdPDPGroup;
57 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
58 import org.openecomp.policy.model.Roles;
59 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
60 import org.openecomp.portalsdk.core.web.support.JsonMessage;
61 import org.openecomp.portalsdk.core.web.support.UserUtils;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.http.MediaType;
64 import org.springframework.stereotype.Controller;
65 import org.springframework.web.bind.annotation.RequestMapping;
66 import org.springframework.web.servlet.ModelAndView;
67
68 import com.att.research.xacml.api.pap.PAPException;
69 import com.att.research.xacml.api.pap.PDPPolicy;
70 import com.fasterxml.jackson.databind.DeserializationFeature;
71 import com.fasterxml.jackson.databind.JsonNode;
72 import com.fasterxml.jackson.databind.ObjectMapper;
73
74
75 @Controller
76 @RequestMapping({"/"})
77 public class AutoPushController extends RestrictedBaseController{
78
79         private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
80         
81         @Autowired
82         CommonClassDao commonClassDao;
83
84         private PDPGroupContainer container;
85         protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
86         
87         private PDPPolicyContainer policyContainer;
88
89         private PolicyController policyController;
90         public PolicyController getPolicyController() {
91                 return policyController;
92         }
93
94         public void setPolicyController(PolicyController policyController) {
95                 this.policyController = policyController;
96         }
97
98         private List<Object> data;
99
100         public synchronized void refreshGroups() {
101                 synchronized(this.groups) { 
102                         this.groups.clear();
103                         try {
104                                 PolicyController controller = getPolicyControllerInstance();
105                                 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
106                         } catch (PAPException e) {
107                                 String message = "Unable to retrieve Groups from server: " + e;
108                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
109                         }
110
111                 }
112         }
113
114         private PolicyController getPolicyControllerInstance(){
115                 return policyController != null ? getPolicyController() : new PolicyController();
116         }
117         
118         @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
119         public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
120                 try{
121                         Set<String> scopes = null;
122                         List<String> roles = null;
123                         data = new ArrayList<Object>();
124                         String userId = UserUtils.getUserSession(request).getOrgUserId();
125                         Map<String, Object> model = new HashMap<>();
126                         ObjectMapper mapper = new ObjectMapper();
127                         PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
128                         List<Object> userRoles = controller.getRoles(userId);
129                         roles = new ArrayList<>();
130                         scopes = new HashSet<>();
131                         for(Object role: userRoles){
132                                 Roles userRole = (Roles) role;
133                                 roles.add(userRole.getRole());
134                                 if(userRole.getScope() != null){
135                                         if(userRole.getScope().contains(",")){
136                                                 String[] multipleScopes = userRole.getScope().split(",");
137                                                 for(int i =0; i < multipleScopes.length; i++){
138                                                         scopes.add(multipleScopes[i]);
139                                                 }
140                                         }else{
141                                                 if(!userRole.getScope().equals("")){
142                                                         scopes.add(userRole.getScope());
143                                                 }
144                                         }               
145                                 }
146                         }
147                         if (roles.contains("super-admin") || roles.contains("super-editor")  || roles.contains("super-guest")) {
148                                 data = commonClassDao.getData(PolicyVersion.class);
149                         }else{
150                                 if(!scopes.isEmpty()){
151                                         for(String scope : scopes){
152                                                 scope += "%";
153                                                 String query = "From PolicyVersion where policy_name like :scope and id > 0";
154                                                 SimpleBindings params = new SimpleBindings();
155                                                 params.put("scope", scope);
156                                                 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
157                                                 if(filterdatas != null){
158                                                         for(int i =0; i < filterdatas.size(); i++){
159                                                                 data.add(filterdatas.get(i));
160                                                         }       
161                                                 }
162                                         }
163                                 }else{
164                                         PolicyVersion emptyPolicyName = new PolicyVersion();
165                                         emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
166                                         data.add(emptyPolicyName);
167                                 }
168                         }
169                         model.put("policydatas", mapper.writeValueAsString(data));
170                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
171                         JSONObject j = new JSONObject(msg);
172                         response.getWriter().write(j.toString());
173                 }
174                 catch (Exception e){
175                         logger.error("Exception Occured"+e);
176                 }
177         }
178
179         @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
180         public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
181                 try {
182                         ArrayList<Object> selectedPDPS = new ArrayList<>();
183                         ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
184                         PolicyController controller = getPolicyControllerInstance();
185                         this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
186                         ObjectMapper mapper = new ObjectMapper();
187                         this.container = new PDPGroupContainer(controller.getPapEngine());
188                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
189                         JsonNode root = mapper.readTree(request.getReader());
190                         AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
191                         for (Object pdpGroupId :  adapter.getPdpDatas()) {
192                                 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
193                                 for(OnapPDPGroup pdpGroup : this.groups){
194                                         if(pdpGroup.getId().equals(selectedPDP.get("id"))){
195                                                 selectedPDPS.add(pdpGroup);
196                                         }
197                                 }
198                         }
199
200                         for (Object policyId :  adapter.getPolicyDatas()) {
201                                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
202                                 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
203                                 selectedPoliciesInUI.add(policyName);
204                         }
205
206                         for (Object pdpDestinationGroupId :  selectedPDPS) {
207                                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
208                                 Set<PDPPolicy> selectedPolicies = new HashSet<>();
209                                 for (String policyId : selectedPoliciesInUI) {
210                                         logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
211                                         
212                                         //
213                                         // Get the current selection
214                                         String selectedItem = policyId;
215                                         //
216                                         assert (selectedItem != null);
217                                         // create the id of the target file
218                                         // Our standard for file naming is:
219                                         // <domain>.<filename>.<version>.xml
220                                         // since the file name usually has a ".xml", we need to strip
221                                         // that
222                                         // before adding the other parts
223                                         String name = selectedItem.replace(File.separator, ".");
224                                         String id = name;
225                                         if (id.endsWith(".xml")) {
226                                                 id = id.replace(".xml", "");
227                                                 id = id.substring(0, id.lastIndexOf("."));
228                                         }
229                                         
230                                         // Default policy to be Root policy; user can change to deferred
231                                         // later
232                                         
233                                         StdPDPPolicy selectedPolicy = null;
234                                         String dbCheckName = name;
235                                         if(dbCheckName.contains("Config_")){
236                                                 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
237                                         }else if(dbCheckName.contains("Action_")){
238                                                 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
239                                         }else if(dbCheckName.contains("Decision_")){
240                                                 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
241                                         }
242                                         String[] split = dbCheckName.split(":");
243                                         String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
244                                         SimpleBindings policyParams = new SimpleBindings();
245                                         policyParams.put("split_1", split[1]);
246                                         policyParams.put("split_0", split[0]);
247                                         List<Object> queryData = controller.getDataByQuery(query, policyParams);
248                                         PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
249                                         File temp = new File(name);
250                                         BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
251                                         bw.write(policyEntity.getPolicyData());
252                                         bw.close();
253                                         URI selectedURI = temp.toURI();
254                                         try {
255                                                 //
256                                                 // Create the policy
257                                                 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
258                                         } catch (IOException e) {
259                                                 logger.error("Unable to create policy '" + name + "': "+ e.getMessage());
260                                         }
261                                         StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
262                                         if (selectedPolicy != null) {
263                                                 // Add Current policies from container
264                                                 for (OnapPDPGroup group : container.getGroups()) {
265                                                         if (group.getId().equals(selectedGroup.getId())) {
266                                                                 currentPoliciesInGroup.addAll(group.getPolicies());
267                                                         }
268                                                 }
269                                                 // copy policy to PAP
270                                                 try {
271                                                         controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
272                                                 } catch (PAPException e) {
273                                                         logger.error("Exception Occured"+e);
274                                                         return null;
275                                                 }
276                                                 selectedPolicies.add(selectedPolicy);
277                                         }
278                                         temp.delete();
279                                 }
280                                 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
281                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
282                                 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
283                                 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
284                                 updatedGroupObject.setStatus(pdpGroup.getStatus());
285
286                                 // replace the original set of Policies with the set from the
287                                 // container (possibly modified by the user)
288                                 // do not allow multiple copies of same policy
289                                 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
290                                 logger.debug("policyIterator....." + selectedPolicies);
291                                 while (policyIterator.hasNext()) {
292                                         PDPPolicy existingPolicy = policyIterator.next();
293                                         for (PDPPolicy selPolicy : selectedPolicies) {
294                                                 if (selPolicy.getName().equals(existingPolicy.getName())) {
295                                                         if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
296                                                                 if (selPolicy.getId().equals(existingPolicy.getId())) {
297                                                                         policyIterator.remove();
298                                                                         logger.debug("Removing policy: " + selPolicy);
299                                                                         break;
300                                                                 }
301                                                         } else {
302                                                                 policyIterator.remove();
303                                                                 logger.debug("Removing Old Policy version: "+ selPolicy);
304                                                                 break;
305                                                         }
306                                                 }
307                                         }
308                                 }
309
310                                 currentPoliciesInGroup.addAll(selectedPolicies);
311                                 updatedGroupObject.setPolicies(currentPoliciesInGroup);
312                                 this.container.updateGroup(updatedGroupObject);
313
314                                 response.setCharacterEncoding("UTF-8");
315                                 response.setContentType("application / json");
316                                 request.setCharacterEncoding("UTF-8");
317
318                                 PrintWriter out = response.getWriter();
319                                 refreshGroups();
320                                 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
321                                 JSONObject j = new JSONObject(msg);
322                                 out.write(j.toString());      
323                                 return null;
324                         }
325                 }
326                 catch (Exception e){
327                         response.setCharacterEncoding("UTF-8");
328                         request.setCharacterEncoding("UTF-8");
329                         PrintWriter out = response.getWriter();
330                         out.write(e.getMessage());
331                 }
332                 return null;
333         }
334
335         @SuppressWarnings("unchecked")
336         @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
337         public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
338                 try {
339                         PolicyController controller = getPolicyControllerInstance();
340                         this.container = new PDPGroupContainer(controller.getPapEngine());
341                         ObjectMapper mapper = new ObjectMapper();
342                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
343                         JsonNode root = mapper.readTree(request.getReader());  
344                         StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
345                         JsonNode removePolicyData = root.get("data");
346                         policyContainer = new PDPPolicyContainer(group);
347                         if(removePolicyData.size() > 0){
348                                 for(int i = 0 ; i < removePolicyData.size(); i++){
349                                         String data = removePolicyData.get(i).toString();
350                                         this.policyContainer.removeItem(data);
351                                 }
352                                 Set<PDPPolicy> changedPolicies = new HashSet<>();
353                                 changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
354                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
355                                 updatedGroupObject.setPolicies(changedPolicies);
356                                 updatedGroupObject.setOnapPdps(group.getOnapPdps());
357                                 updatedGroupObject.setPipConfigs(group.getPipConfigs());
358                                 updatedGroupObject.setStatus(group.getStatus());
359                                 this.container.updateGroup(updatedGroupObject);
360                         }
361                         
362                         response.setCharacterEncoding("UTF-8");
363                         response.setContentType("application / json");
364                         request.setCharacterEncoding("UTF-8");
365
366                         PrintWriter out = response.getWriter();
367                         refreshGroups();
368                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
369                         JSONObject j = new JSONObject(msg);
370
371                         out.write(j.toString());
372
373                         return null;
374                 }
375                 catch (Exception e){
376                         response.setCharacterEncoding("UTF-8");
377                         request.setCharacterEncoding("UTF-8");
378                         PrintWriter out = response.getWriter();
379                         out.write(e.getMessage());
380                 }
381                 return null;
382         }
383
384 }