Resubmitting KeyProperty code change since tests failed
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / service / sessionmgt / SessionCommunication.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.service.sessionmgt;
39
40 import java.io.BufferedReader;
41 import java.io.InputStreamReader;
42 import java.net.HttpURLConnection;
43 import java.net.URL;
44 import java.util.Base64;
45 import java.util.HashMap;
46 import java.util.Map;
47 import java.util.UUID;
48
49 import javax.servlet.http.HttpServletResponse;
50
51 import org.onap.portalapp.portal.domain.EPApp;
52 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
53 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
54 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
55 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
56 import org.onap.portalapp.portal.service.AppsCacheService;
57 import org.onap.portalapp.portal.transport.OnboardingApp;
58 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
59 import org.onap.portalapp.portal.utils.EcompPortalUtils;
60 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
63 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
64 import org.onap.portalsdk.core.onboarding.util.KeyConstants;
65 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
66 import org.onap.portalsdk.core.util.SystemProperties;
67 import org.slf4j.MDC;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.context.annotation.EnableAspectJAutoProxy;
70 import org.springframework.stereotype.Service;
71 import org.apache.commons.lang.StringUtils;
72
73 import com.att.eelf.configuration.Configuration;
74
75 @Service("sessionCommunication")
76 @org.springframework.context.annotation.Configuration
77 @EnableAspectJAutoProxy
78 public class SessionCommunication {
79         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCommunication.class);
80         @Autowired
81         private AppsCacheService appsCacheService;
82         
83         private static final String BASIC_AUTHENTICATION_HEADER = "Authorization";
84
85         @EPAuditLog
86         public String sendGet(OnboardingApp app) throws Exception {
87                 String appResponse = "";
88                 String appName = "";
89                 int responseCode = 0;
90                 if (app != null && app.getAppName() != null && app.getAppName() != "") {
91                         try {
92                                 appName = app.getAppName();
93                                 String url = app.getRestUrl() + "/sessionTimeOuts";
94                                 String encriptedPwdDB = app.getAppBasicAuthPassword();
95                                 String appUserName = app.getAppBasicAuthUsername();
96
97                                 setLocalMDCContext(app, "/sessionTimeOuts", url);
98
99                                 URL obj = new URL(url);
100
101                                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
102
103                                 // optional default is GET
104                                 con.setRequestMethod("GET");
105                                 con.setConnectTimeout(3000);
106                                 con.setReadTimeout(8000);
107                                 // add request header
108                                 Map<String,String> headers = getHeaders(app);
109                                 appUserName =headers.get("username");
110                                 encriptedPwdDB = headers.get("password");
111                                 
112                                 con.setRequestProperty("username", appUserName);
113                                 con.setRequestProperty("password", encriptedPwdDB);
114
115                                 
116                                 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
117                                 String encodingStr = "Basic " + encoding;
118                                 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
119
120                                 // con.set
121                                 responseCode = con.getResponseCode();
122                                 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
123
124                                 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
125                                 String inputLine;
126                                 StringBuffer response = new StringBuffer();
127
128                                 while ((inputLine = in.readLine()) != null) {
129                                         response.append(inputLine);
130                                 }
131
132                                 in.close();
133                                 appResponse = response.toString();
134                         } catch (UrlAccessRestrictedException e) {
135                                 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
136                                 logger.error(EELFLoggerDelegate.errorLogger, String.format(
137                                                 "SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName));
138                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
139                         } catch (Exception e) {
140                                 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
141                                 String message = String.format(
142                                                 "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName,
143                                                 e.toString());
144                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
145                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
146                         } finally {
147                                 EcompPortalUtils.setExternalAppResponseCode(responseCode);
148                         }
149                 } else {
150                         logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication sendGet: app is null");
151                 }
152                 return appResponse;
153         }
154
155         @EPAuditLog
156         public Boolean pingSession(OnboardingApp app, String sessionTimeoutMap) throws Exception {
157                 String appName = "";
158                 int responseCode = 0;
159                 try {
160                         if (app == null)
161                                 throw new Exception("SessionCommunication.pingSession: app is null");
162                         if (app != null && app.getAppName() != null && app.getAppName() != "") {
163                                 appName = app.getAppName();
164                         }
165                         String url = app.getRestUrl() + "/updateSessionTimeOuts";
166                         String encriptedPwdDB = app.getAppBasicAuthPassword();
167                         String appUserName = app.getAppBasicAuthUsername();
168
169                         setLocalMDCContext(app, "/updateSessionTimeOuts", url);
170
171                         URL obj = new URL(url);
172
173                         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
174
175                         // optional default is GET
176                         con.setRequestMethod("POST");
177                         con.setConnectTimeout(3000);
178                         con.setReadTimeout(15000);
179
180                         Map<String,String> headers = getHeaders(app);
181                         appUserName =headers.get("username");
182                         encriptedPwdDB = headers.get("password");
183                         
184                         con.setRequestProperty("username", appUserName);
185                         con.setRequestProperty("password", encriptedPwdDB);
186                         
187                         String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
188                         String encodingStr = "Basic " + encoding;
189                         con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
190
191                         con.setRequestProperty("sessionMap", sessionTimeoutMap);
192                         con.setDoInput(true);
193                         con.setDoOutput(true);
194                         con.getOutputStream().write(sessionTimeoutMap.getBytes());
195                         con.getOutputStream().flush();
196                         con.getOutputStream().close();
197
198                         responseCode = con.getResponseCode();
199                         logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
200                 } catch (UrlAccessRestrictedException e) {
201                         responseCode = HttpServletResponse.SC_UNAUTHORIZED;
202                         String message = String.format(
203                                         "SessionCommunication.pingSession received an un-authorized exception. AppName: %s", appName);
204                         logger.error(EELFLoggerDelegate.errorLogger, message);
205                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
206                 } catch (Exception e) {
207                         responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
208                         String message = String.format(
209                                         "SessionCommunication.pingSession encountered an Exception. AppName: %s, Details: %s", appName, e.toString());
210                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
211                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
212                 } finally {
213                         EcompPortalUtils.setExternalAppResponseCode(responseCode);
214                 }
215
216                 return true;
217         }
218
219         @EPAuditLog
220         public Boolean timeoutSession(OnboardingApp app, String portalJSessionId) throws Exception {
221                 String appName = "Unknwon";
222                 int responseCode = 0;
223                 if (app != null && app.getAppName() != null && app.getAppName() != "") {
224                         try {
225                                 appName = app.getAppName();
226                                 String url = app.getRestUrl() + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId;
227
228                                 String encriptedPwdDB = app.getAppBasicAuthPassword();
229                                 String appUserName = app.getAppBasicAuthUsername();
230                                 // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
231                                 // SystemProperties.getProperty(SystemProperties.Decryption_Key));
232
233                                 setLocalMDCContext(app, "/timeoutSession", url);
234
235                                 URL obj = new URL(url);
236                                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
237
238                                 // optional default is GET
239                                 con.setRequestMethod("POST");
240                                 con.setConnectTimeout(3000);
241                                 con.setReadTimeout(15000);
242
243                                 Map<String,String> headers = getHeaders(app);
244                                 appUserName =headers.get("username");
245                                 encriptedPwdDB = headers.get("password");
246                                 
247                                 con.setRequestProperty("username", appUserName);
248                                 con.setRequestProperty("password", encriptedPwdDB);
249                                 
250                                 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
251                                 String encodingStr = "Basic " + encoding;
252                                 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
253                                 
254                                 con.setDoInput(true);
255                                 con.setDoOutput(true);
256                                 con.getOutputStream().flush();
257                                 con.getOutputStream().close();
258
259                                 responseCode = con.getResponseCode();
260                                 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
261                         } catch (UrlAccessRestrictedException e) {
262                                 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
263                                 String message = String.format(
264                                                 "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s",
265                                                 appName);
266                                 logger.error(EELFLoggerDelegate.errorLogger, message);
267                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
268                         } catch (Exception e) {
269                                 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
270                                 String message = String.format(
271                                                 "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s", 
272                                                 appName, e.toString());
273                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
274                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
275                         } finally {
276                                 EcompPortalUtils.setExternalAppResponseCode(responseCode);
277                         }
278                 } else {
279                         logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication pingSession: app is null");
280                 }
281                 return true;
282         }
283
284         @EPMetricsLog
285         private void setLocalMDCContext(OnboardingApp app, String restPath, String url) {
286                 setRequestId();
287                 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
288                 if (url != null && url.contains("https")) {
289                         MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
290                 }
291                 MDC.put(EPCommonSystemProperties.FULL_URL, url);
292                 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, app.getMyLoginsAppName());
293                 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);
294         }
295
296         /**
297          * Generates request id, service name fields and loads them into MDC, as these
298          * values could be empty as these session timeout requests are generated at
299          * scheduled intervals using quartz scheduler.
300          */
301         @EPMetricsLog
302         public void setRequestId() {
303                 String requestId = MDC.get(Configuration.MDC_KEY_REQUEST_ID);
304                 if (StringUtils.isEmpty(requestId)) {
305                         MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.randomUUID().toString());
306                 }
307
308                 MDC.put(Configuration.MDC_SERVICE_NAME, "/quartz/keepSessionAlive");
309                 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
310         }
311
312         /**
313          * Remove the values from MDC as these requests are executed at regular
314          * intervals based on quartz rather incoming REST API requests.
315          * 
316          * @param bAll
317          */
318         @EPMetricsLog
319         public void clear(Boolean bAll) {
320                 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
321                 if (bAll) {
322                         MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
323                         MDC.remove(Configuration.MDC_SERVICE_NAME);
324                         MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
325                 }
326         }
327         
328         public Map<String,String> getHeaders(OnboardingApp app)
329         {
330                 String encriptedPwdDB = "";
331                 String appUserName = "";
332
333                 
334                  Map<String,String> headersMap = new HashMap<>();
335                 EPApp externalApp = null;
336
337                 if(app.getAppBasicAuthPassword().isEmpty() || app.getAppBasicAuthPassword()==null){
338                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the externalApp get app password contains null : {}");
339                         externalApp = appsCacheService.getApp(1L);
340                         logger.debug(EELFLoggerDelegate.debugLogger, "external App Information : {}",externalApp);
341
342                         String mechidUsername=externalApp.getAppBasicAuthUsername();
343                         logger.debug(EELFLoggerDelegate.debugLogger, "external App mechidUsername Information : {}",mechidUsername);
344
345                         String password=externalApp.getAppBasicAuthPassword();
346                         String decreptedexternalAppPwd = StringUtils.EMPTY;
347                         try {
348                                 decreptedexternalAppPwd = CipherUtil.decryptPKC(password,
349                                                 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
350                         } catch (CipherUtilException e) {
351                                 logger.error(EELFLoggerDelegate.errorLogger, "failed to decreptedexternalAppPwd when external app pwd is null", e);
352                         }
353                         
354                         appUserName =mechidUsername;
355                         encriptedPwdDB = decreptedexternalAppPwd;
356                 
357                 }else{
358                         appUserName = app.getAppBasicAuthUsername();
359                         encriptedPwdDB = app.getAppBasicAuthPassword();
360                 }
361                 
362                 headersMap.put("username", appUserName);
363                 headersMap.put("password", encriptedPwdDB);
364                 return headersMap;
365         }
366 }