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