Resubmitting KeyProperty code change since tests failed
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / interceptor / PortalResourceInterceptor.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * 
7  * Modification Copyright (C) 2018 IBM.
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  * 
39  */
40 package org.onap.portalapp.portal.interceptor;
41
42 import java.util.HashMap;
43 import java.util.Set;
44
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47
48 import org.onap.aaf.cadi.CadiWrap;
49 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
50 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
51 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
52 import org.onap.portalapp.portal.controller.SharedContextRestController;
53 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
54 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
55 import org.onap.portalapp.portal.domain.EPApp;
56 import org.onap.portalapp.portal.domain.EPUser;
57 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
58 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
59 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
60 import org.onap.portalapp.portal.service.AdminRolesService;
61 import org.onap.portalapp.portal.service.AppsCacheService;
62 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
63 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
64 import org.onap.portalapp.portal.utils.EcompPortalUtils;
65 import org.onap.portalapp.service.RemoteWebServiceCallService;
66 import org.onap.portalapp.service.sessionmgt.ManageService;
67 import org.onap.portalapp.util.EPUserUtils;
68 import org.onap.portalsdk.core.controller.FusionBaseController;
69 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
70 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
71 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
72 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
73 import org.onap.portalsdk.core.onboarding.util.AuthUtil;
74 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
75 import org.onap.portalsdk.core.onboarding.util.KeyConstants;
76 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
77 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
78 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
79 import org.onap.portalsdk.core.util.SystemProperties;
80 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.web.method.HandlerMethod;
83
84 public class PortalResourceInterceptor extends ResourceInterceptor {
85         
86         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
87
88         @Autowired
89         private RemoteWebServiceCallService remoteWebServiceCallService;
90
91         @Autowired
92         private ManageService manageService;
93         
94         @Autowired
95         AppsCacheService appCacheService;
96
97         @Autowired
98         private EPEELFLoggerAdvice epAdvice;
99         
100         @Autowired
101         private AdminRolesService adminRolesService;
102
103         @Autowired
104         private BasicAuthenticationCredentialService basicAuthService;
105
106         @SuppressWarnings("unchecked")
107         @Override
108         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
109                         throws Exception {
110
111                 if (handler instanceof HandlerMethod) {
112                         HandlerMethod method = (HandlerMethod) handler;
113
114                         /**
115                          * These classes provide REST endpoints used by other application
116                          * servers, NOT by an end user's browser.
117                          */
118                         if (method.getBean() instanceof FusionBaseController) {
119                                 FusionBaseController controller = (FusionBaseController) method.getBean();
120                                 if (!controller.isAccessible()) {
121
122                                         // authorize portalApi requests by user role
123                                         String requestURI = request.getRequestURI();
124                                         if (requestURI != null) {
125                                                 String[] uriArray = requestURI.split("/portalApi/");
126                                                 if (uriArray.length > 1) {
127                                                         String portalApiPath = uriArray[1];
128
129                                                         Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
130                                                                         .getAttribute(SystemProperties
131                                                                                         .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
132                                                         Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
133                                                                         .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
134                                                         // Defend against code error to avoid throwing NPE
135                                                         if (roleFunctions == null || allRoleFunctions == null) {
136                                                                 logger.error(EELFLoggerDelegate.errorLogger,
137                                                                                 "preHandle: failed to get role functions attribute(s) from session!!");
138                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
139                                                                 return false;
140                                                         }
141                                                         // check to see if roleFunctions of the user is in
142                                                         // the
143                                                         // list of all role functions
144                                                         // if not, ignore to prevent restricting every
145                                                         // trivial
146                                                         // call; otherwise, if it is, then check for the
147                                                         // access
148                                                         EPUser user = (EPUser) request.getSession().getAttribute(
149                                                                         SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
150                                                         //RoleAdmin check is being added because the role belongs to partner application 
151                                                         //inorder to access portal api's, bypassing this with isRoleAdmin Check
152                                                         if ((EPUserUtils.matchRoleFunctions(portalApiPath, allRoleFunctions)
153                                                                         && !EPUserUtils.matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) {
154                                                                 logger.error(EELFLoggerDelegate.errorLogger,
155                                                                                 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
156                                                                                 portalApiPath);
157                                                                 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
158                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
159                                                                 return false;
160                                                         } // failed to match
161
162                                                 } // is portalApi
163
164                                         } // requestURI
165                                 } // instance check
166                         } // not accessible
167                         else if (method.getBean() instanceof BasicAuthenticationController) {
168                                 return checkBasicAuth(request, response);
169                         }
170                         Object controllerObj = method.getBean();
171                         if (controllerObj instanceof SessionCommunicationController
172                                         || controllerObj instanceof SharedContextRestController
173                                         || controllerObj instanceof ExternalAppsRestfulController) {
174                                 // check user authentication for RESTful calls
175                                 String secretKey = null;
176                                 try {
177                                         epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
178                                         if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
179                                                         request.getHeader("username"), request.getHeader("password"))) {
180                                                 throw new UrlAccessRestrictedException();
181                                         }
182                                 } catch (Exception e) {
183                                         logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
184                                                         e);
185                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
186                                         throw new UrlAccessRestrictedException();
187                                 }
188                         }
189
190                         if (controllerObj instanceof WebAnalyticsExtAppController) {
191                                 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(EPCommonSystemProperties.UEB_KEY))) {
192                                         logger.error(EELFLoggerDelegate.errorLogger,
193                                                         "preHandle: failed to verify app key for web analytics call");
194                                         throw new UrlAccessRestrictedException();
195                                 }
196                         }
197                 }
198
199                 handleSessionUpdates(request);
200                 return true;
201         }
202
203         /**
204          * Sets the status code and sends a response. Factors code out of many
205          * methods.
206          * 
207          * @param response
208          *            HttpServletResponse
209          * @param statusCode
210          *            HTTP status code like 404
211          * @param message
212          *            Message to send in a JSON error object
213          */
214         private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
215                         throws Exception {
216                 response.setStatus(statusCode);
217                 response.setContentType("application/json");
218                 response.getWriter().write("{\"error\":\"" + message + "\"}");
219                 response.getWriter().flush();
220         }
221
222         /**
223          * Gets HTTP basic authentication information from the request and checks
224          * whether those credentials are authorized for the request path.
225          * 
226          * @param request
227          *            HttpServletRequest
228          * @param response
229          *            HttpServletResponse
230          * @return True if the request is authorized, else false
231          * @throws Exception
232          */
233         private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
234                 String uri = request.getRequestURI().toString();
235                 uri = uri.substring(uri.indexOf("/", 1));
236
237                 final String authHeader = request.getHeader(EPCommonSystemProperties.AUTHORIZATION);
238                 final String uebkey = request.getHeader(EPCommonSystemProperties.UEB_KEY);
239                 try{
240                         CadiWrap wrapReq = (CadiWrap) request;
241                                 logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the loop as the uri contains auxapi : {}");
242                                 String nameSpace=PortalApiProperties.getProperty(PortalApiConstants.AUTH_NAMESPACE);
243                                 logger.debug(EELFLoggerDelegate.debugLogger, "namespace form the portal properties : {}",nameSpace);
244                                 Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace, new HashMap<>());
245                                 logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed for the request and namespace : {}",accessallowed);
246                                 if(accessallowed){
247                                         logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed is allowed: {}",accessallowed);
248
249                                         //String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
250                                         //check ueb condition
251                                         if(uebkey !=null && !uebkey.isEmpty())
252                                         {
253                                                 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
254                                                 if (application == null) {
255                                                         throw new Exception("Invalid credentials!");
256                                                 }
257                                                 else {
258                                                         final String appUsername = application.getAppBasicAuthUsername();
259                                                         logger.debug(EELFLoggerDelegate.debugLogger, "appUsername : {}",appUsername);
260
261                                                         String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
262                                                         logger.debug(EELFLoggerDelegate.debugLogger, "accountNamePassword : {}",accountNamePassword);
263
264                                                         if (accountNamePassword == null || accountNamePassword.length != 2) {
265                                                                 final String msg = "failed to get username and password from Atuhorization header";
266                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth Username and password failed to get: {}", msg);
267                                                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
268                                                                 return false;
269                                                         }
270                                                         if (appUsername.equals(accountNamePassword[0])) {
271                                                                 return true;
272                                                         }else{
273                                                                 final String msg = "failed to match the UserName from the application ";
274                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "failed to match the UserName from the application checkBasicAuth Username and password failed to get: {}", msg);
275                                                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
276                                                                 return false;
277                                                         }
278                                                 }
279                                         }
280
281                                         return true;    
282                                 }
283                                 if(!accessallowed){
284                                         final String msg = "no authorization found";
285                                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth when no accessallowed: {}", msg);
286                                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
287                                         return false;
288                                 }
289                                 return false;
290                         
291                 }catch(ClassCastException e){
292                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the classcastexception block if the UN is not the mechid : {}");
293
294                         String secretKey = null;
295                         // Unauthorized access due to missing HTTP Authorization request header
296                         if (authHeader == null) {
297                                 if (remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
298                                                 request.getHeader("username"), request.getHeader("password"))) {
299                                         return true;
300                                 }
301                                 final String msg = "no authorization found";
302                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
303                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
304                                 return false;
305                         }
306
307                         String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
308                         if (accountNamePassword == null || accountNamePassword.length != 2) {
309                                 final String msg = "failed to get username and password from Atuhorization header";
310                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
311                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
312                                 return false;
313                         }
314
315                         if(uebkey !=null && !uebkey.isEmpty())
316                         {
317                                 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
318                                 if (application == null) {
319                                         throw new Exception("Invalid credentials!");
320                                 }
321                                 else {
322                                         final String appUsername = application.getAppBasicAuthUsername();
323                                         final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppBasicAuthPassword());
324                                         if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
325                                                 return true;
326                                         }
327                                 }
328                         }
329
330                         
331                         BasicAuthCredentials creds;
332                         try {
333                                 creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
334                                                 accountNamePassword[1]);
335                         } catch (Exception e1) {
336                                 logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e1);
337                                 final String msg = "Failed while getting basic authentication credential: ";
338                                 sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
339                                 throw e1;
340                         }
341
342                         // Unauthorized access due to invalid credentials (username and
343                         // password)
344                         if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
345                                 final String msg = "Unauthorized: Access denied";
346                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
347                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
348                                 return false;
349                         }
350
351                         // Unauthorized access due to inactive account
352                         if (creds.getIsActive().equals("N")) {
353                                 final String msg = "Unauthorized: The account is inactive";
354                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
355                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
356                                 return false;
357                         }
358                 
359                 }catch (Exception e2) {
360                         logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials for some other exception", e2);
361                         final String msg = "Failed while getting basic authentication credential for some other exception: ";
362                         sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
363                         throw e2;
364                 }
365                 return true;
366
367
368 }
369
370         @SuppressWarnings("unused")
371         private String decrypted(String encrypted) throws Exception {
372                 String result = "";
373                 if (encrypted != null && encrypted.length() > 0) {
374                         try {
375                                 result = CipherUtil.decryptPKC(encrypted, KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
376                         } catch (Exception e) {
377                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
378                                 throw e;
379                         }
380                 }
381                 return result;
382         }
383
384         private String encrypted(String decryptedPwd) throws Exception {
385                 String result = "";
386                 if (decryptedPwd != null && decryptedPwd.length() > 0) {
387                         try {
388                                 result = CipherUtil.encryptPKC(decryptedPwd,
389                                                 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
390                         } catch (Exception e) {
391                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
392                                 throw e;
393                         }
394                 }
395                 return result;
396         }
397
398         protected void handleSessionUpdates(HttpServletRequest request) {
399                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
400         }
401         
402 }