Merge "Implement Encryption on Passwords"
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / UpdateOthersPAPS.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2018 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 package org.onap.policy.pap.xacml.rest;
21
22 import java.io.BufferedWriter;
23 import java.io.File;
24 import java.io.FileWriter;
25 import java.io.IOException;
26 import java.nio.charset.StandardCharsets;
27 import java.nio.file.Files;
28 import java.nio.file.Paths;
29 import java.util.Base64;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36
37 import org.json.JSONObject;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 import org.onap.policy.pap.xacml.rest.adapters.UpdateObjectData;
41 import org.onap.policy.pap.xacml.rest.components.Policy;
42 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
43 import org.onap.policy.rest.XACMLRestProperties;
44 import org.onap.policy.rest.dao.CommonClassDao;
45 import org.onap.policy.rest.jpa.ActionBodyEntity;
46 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
47 import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
48 import org.onap.policy.utils.CryptoUtils;
49 import org.onap.policy.xacml.api.XACMLErrorConstants;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.http.HttpEntity;
52 import org.springframework.http.HttpHeaders;
53 import org.springframework.http.HttpMethod;
54 import org.springframework.http.HttpStatus;
55 import org.springframework.stereotype.Controller;
56 import org.springframework.web.bind.annotation.RequestBody;
57 import org.springframework.web.bind.annotation.RequestMapping;
58 import org.springframework.web.bind.annotation.RequestMethod;
59 import org.springframework.web.bind.annotation.ResponseBody;
60 import org.springframework.web.client.HttpClientErrorException;
61 import org.springframework.web.client.RestTemplate;
62
63 import com.fasterxml.jackson.databind.ObjectMapper;
64
65 @Controller
66 public class UpdateOthersPAPS {
67         
68         private static final Logger     policyLogger    = FlexLogger.getLogger(UpdateOthersPAPS.class);
69         
70         private static CommonClassDao commonClassDao;
71         
72         private static final String contentType = "application/json";
73         private static String configType =".Config_";
74         private static String actionType =".Action_";
75         private static String error ="error";
76         public static CommonClassDao getCommonClassDao() {
77                 return commonClassDao;
78         }
79
80         public static void setCommonClassDao(CommonClassDao commonClassDao) {
81                 UpdateOthersPAPS.commonClassDao = commonClassDao;
82         }
83
84         @Autowired
85         private UpdateOthersPAPS(CommonClassDao commonClassDao){
86                 UpdateOthersPAPS.commonClassDao = commonClassDao;
87         }
88         
89         public UpdateOthersPAPS() {
90                 //Empty Constructor
91         }
92
93         @RequestMapping(value="/notifyOtherPAPs", method= RequestMethod.POST)
94         public void  notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response){
95                 Map<String, Object> model = new HashMap<>();
96                 ObjectMapper mapper = new ObjectMapper();
97                 UpdateObjectData body = new UpdateObjectData();
98                 body.setAction(request.getParameter("action"));
99                 body.setNewPolicyName(request.getParameter("newPolicyName"));
100                 body.setOldPolicyName(request.getParameter("oldPolicyName"));
101
102                 String currentPap = XACMLRestProperties.getProperty("xacml.rest.pap.url");
103                 List<Object> getPAPUrls = commonClassDao.getData(PolicyDBDaoEntity.class);
104                 if(getPAPUrls != null && !getPAPUrls.isEmpty()){
105                         for(int i = 0; i < getPAPUrls.size(); i++){
106                                 PolicyDBDaoEntity papId = (PolicyDBDaoEntity) getPAPUrls.get(i);
107                                 String papUrl = papId.getPolicyDBDaoUrl();
108                                 if(!papUrl.equals(currentPap)){
109                                         String userName = papId.getUsername();
110                                         String password = papId.getPassword();
111                                         Base64.Encoder encoder = Base64.getEncoder();
112                                         String txt;
113                                         try{
114                                                 txt = new String(CryptoUtils.decryptTxt(password), StandardCharsets.UTF_8);
115                                         } catch(Exception e){
116                                                 policyLogger.debug(e);
117                                                 //if we can't decrypt, might as well try it anyway
118                                                 txt = password;
119                                         }
120                                         String encoding = encoder.encodeToString((userName+":"+txt).getBytes(StandardCharsets.UTF_8));
121                                         HttpHeaders headers = new HttpHeaders();
122                                         headers.set("Authorization", "Basic " + encoding);
123                                         headers.set("Content-Type", contentType);
124
125                                         RestTemplate restTemplate = new RestTemplate();
126                                         HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
127                                         HttpClientErrorException exception = null;
128
129                                         try{
130                                                 restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity, String.class);
131                                         }catch(Exception e){
132                                                 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
133                                                 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
134                                                 if("409 Conflict".equals(e.getMessage())){
135                                                         policyLogger.error(e.getMessage());
136                                     response.addHeader(error, e.getMessage());
137                                                 }
138                                         }
139                                         if(exception != null && exception.getStatusCode()!=null){
140                                                 String message;
141                                                 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
142                                                         message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
143                                                         policyLogger.error(message);
144                                                 }else if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
145                                                         message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
146                                                         policyLogger.error(message);
147                                                 }else if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
148                                                         message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
149                                                         policyLogger.error(message);
150                                                 }else{
151                                                         message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
152                                                         policyLogger.error(message);
153                                                 }
154                                                 model.put(papUrl, message);
155                                         }else{
156                                                 model.put(papUrl, "Success");
157                                         }
158                                 }
159                         }
160                         JsonMessage msg;
161                         try {
162                                 msg = new JsonMessage(mapper.writeValueAsString(model));
163                                 JSONObject j = new JSONObject(msg);
164                                 response.getWriter().write(j.toString());
165                         } catch (Exception e) {
166                                 policyLogger.error("Exception Occured"+e);
167                         }
168                 }
169         }
170         
171         @RequestMapping(value="/updateConfiguration", method= RequestMethod.POST)
172         @ResponseBody
173         public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response){
174                 String action = data.getAction();
175                 String newPolicyName = data.getNewPolicyName();
176                 String oldPolicyName = data.getOldPolicyName();
177                 try{
178                         if("rename".equals(action)){
179                                 if(oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)){
180                                         File file;
181                                         if(oldPolicyName.contains(configType)){
182                                                 file = new File(Policy.getConfigHome() + File.separator + oldPolicyName);
183                                         }else{
184                                                 file = new File(Policy.getActionHome() + File.separator + oldPolicyName);
185                                         }
186                                         if(file.exists()){
187                                                 File renamefile;
188                                                 if(oldPolicyName.contains(configType)){
189                                                         renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName);
190                                                 }else{
191                                                         renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName);
192                                                 }
193                                                 if(file.renameTo(renamefile)){
194                                                         policyLogger.info("Policy has been renamed Successfully"+newPolicyName);
195                                                         response.addHeader("rename", "Success");
196                                                 }else{
197                                                         response.addHeader("rename", "Failure");
198                                                 }
199                                         }
200                                 }
201                         }else if("delete".equals(action)){
202                                 if(oldPolicyName.contains(configType)){
203                                         Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName));
204                                 }else if(oldPolicyName.contains("Action_")){
205                                         Files.deleteIfExists(Paths.get(Policy.getActionHome() + File.separator + oldPolicyName));
206                                 }
207                         }else if("clonePolicy".equals(action) || "exportPolicy".equals(action)){
208                                 if(newPolicyName.contains(configType)){
209                                         ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName);
210                                         saveConfigurationData(configEntiy, newPolicyName);
211                                 }else if(newPolicyName.contains(actionType)){
212                                         ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName);
213                                         saveActionBodyData(actionEntiy, newPolicyName);
214                                 }
215                         }
216                 } catch (IOException e) {
217                         policyLogger.error("Exception Occured While updating Configuration"+e);
218                 }
219         }
220         
221         private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName){
222                 try(FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)){
223                         BufferedWriter bw = new BufferedWriter(fw);
224                         bw.write(configEntiy.getConfigBody());
225                         bw.close();
226                 }catch (IOException e) {
227                         policyLogger.error("Exception Occured While closing the File input stream"+e);
228                 }
229         }
230         
231         private void saveActionBodyData(ActionBodyEntity actionEntiy , String newPolicyName){
232                 try(FileWriter fw  = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)){
233                         BufferedWriter bw = new BufferedWriter(fw);
234                         bw.write(actionEntiy.getActionBody());
235                         bw.close();
236                 }catch (IOException e) {
237                         policyLogger.error("Exception Occured While closing the File input stream"+e);
238                 }
239         }
240 }