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