Sonar fix in RoleApp.Java
[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  *
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.portal.interceptor;
39
40 import java.nio.charset.Charset;
41 import java.util.ArrayList;
42 import java.util.Base64;
43 import java.util.List;
44 import java.util.Set;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
47 import java.util.stream.Collectors;
48
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
52 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
53 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
54 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
55 import org.onap.portalapp.portal.controller.SharedContextRestController;
56 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
57 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
58 import org.onap.portalapp.portal.domain.EPApp;
59 import org.onap.portalapp.portal.domain.EPEndpoint;
60 import org.onap.portalapp.portal.domain.EPUser;
61 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
62 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
63 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
64 import org.onap.portalapp.portal.service.AppsCacheService;
65 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
66 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
67 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
68 import org.onap.portalapp.portal.utils.EcompPortalUtils;
69 import org.onap.portalapp.service.RemoteWebServiceCallService;
70 import org.onap.portalapp.service.sessionmgt.ManageService;
71 import org.onap.portalapp.util.EPUserUtils;
72 import org.onap.portalsdk.core.controller.FusionBaseController;
73 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
74 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
75 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
76 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
77 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
78 import org.onap.portalsdk.core.util.SystemProperties;
79 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
80 import org.springframework.beans.factory.annotation.Autowired;
81 import org.springframework.web.method.HandlerMethod;
82
83 public class PortalResourceInterceptor extends ResourceInterceptor {
84         
85         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
86
87         @Autowired
88         private RemoteWebServiceCallService remoteWebServiceCallService;
89
90         @Autowired
91         private ManageService manageService;
92         
93         @Autowired
94         AppsCacheService appCacheService;
95
96         @Autowired
97         private EPEELFLoggerAdvice epAdvice;
98
99         @Autowired
100         private BasicAuthenticationCredentialService basicAuthService;
101         @Autowired
102         private ExternalAccessRolesService externalAccessRolesService;
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                                                         if (matchRoleFunctions(portalApiPath, allRoleFunctions)
147                                                                         && !matchRoleFunctions(portalApiPath, roleFunctions)) {
148                                                                 EPUser user = (EPUser) request.getSession().getAttribute(
149                                                                                 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
150                                                                 logger.error(EELFLoggerDelegate.errorLogger,
151                                                                                 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
152                                                                                 portalApiPath);
153                                                                 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
154                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
155                                                                 return false;
156                                                         } // failed to match
157
158                                                 } // is portalApi
159
160                                         } // requestURI
161                                 } // instance check
162                         } // not accessible
163                         else if (method.getBean() instanceof BasicAuthenticationController) {
164                                 return checkBasicAuth(request, response);
165                         }
166                         Object controllerObj = method.getBean();
167                         if (controllerObj instanceof SessionCommunicationController
168                                         || controllerObj instanceof SharedContextRestController
169                                         || controllerObj instanceof ExternalAppsRestfulController) {
170                                 // check user authentication for RESTful calls
171                                 String secretKey = null;
172                                 try {
173                                         epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
174                                         if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
175                                                         request.getHeader("username"), request.getHeader("password"))) {
176                                                 throw new UrlAccessRestrictedException();
177                                         }
178                                 } catch (Exception e) {
179                                         logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
180                                                         e);
181                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
182                                         throw new UrlAccessRestrictedException();
183                                 }
184                         }
185
186                         if (controllerObj instanceof WebAnalyticsExtAppController) {
187                                 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(EPCommonSystemProperties.UEB_KEY))) {
188                                         logger.error(EELFLoggerDelegate.errorLogger,
189                                                         "preHandle: failed to verify app key for web analytics call");
190                                         throw new UrlAccessRestrictedException();
191                                 }
192                         }
193                 }
194
195                 handleSessionUpdates(request);
196                 return true;
197         }
198
199         /**
200          * Sets the status code and sends a response. Factors code out of many
201          * methods.
202          * 
203          * @param response
204          *            HttpServletResponse
205          * @param statusCode
206          *            HTTP status code like 404
207          * @param message
208          *            Message to send in a JSON error object
209          */
210         private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
211                         throws Exception {
212                 response.setStatus(statusCode);
213                 response.setContentType("application/json");
214                 response.getWriter().write("{\"error\":\"" + message + "\"}");
215                 response.getWriter().flush();
216         }
217
218         /**
219          * Gets HTTP basic authentication information from the request and checks
220          * whether those credentials are authorized for the request path.
221          * 
222          * @param request
223          *            HttpServletRequest
224          * @param response
225          *            HttpServletResponse
226          * @return True if the request is authorized, else false
227          * @throws Exception
228          */
229         private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
230                 String uri = request.getRequestURI().toString();
231                 uri = uri.substring(uri.indexOf("/", 1));
232
233                 final String authHeader = request.getHeader(EPCommonSystemProperties.AUTHORIZATION);
234                 final String uebkey = request.getHeader(EPCommonSystemProperties.UEB_KEY);
235                 
236                 // Unauthorized access due to missing HTTP Authorization request header
237                 if (authHeader == null) {
238                         final String msg = "no authorization found";
239                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
240                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
241                         return false;
242                 }
243
244                 String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
245                 if (accountNamePassword == null || accountNamePassword.length != 2) {
246                         final String msg = "failed to get username and password from Atuhorization header";
247                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
248                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
249                         return false;
250                 }
251
252                 if(uebkey !=null && !uebkey.isEmpty())
253                 {
254                         EPApp application = appCacheService.getAppFromUeb(uebkey,1);
255                         if (application == null) {
256                                 throw new Exception("Invalid uebkey!");
257                         }
258                         else {
259                                 final String appUsername = application.getUsername();
260                                 final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
261                                 if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
262                                         return true;
263                                 }
264                         }
265                 }
266
267                 
268                 BasicAuthCredentials creds;
269                 try {
270                         creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
271                                         accountNamePassword[1]);
272                 } catch (Exception e) {
273                         logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
274                         final String msg = "Failed while getting basic authentication credential: ";
275                         sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
276                         throw e;
277                 }
278
279                 // Unauthorized access due to invalid credentials (username and
280                 // password)
281                 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
282                         final String msg = "Unauthorized: Access denied";
283                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
284                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
285                         return false;
286                 }
287
288                 // Unauthorized access due to inactive account
289                 if (creds.getIsActive().equals("N")) {
290                         final String msg = "Unauthorized: The account is inactive";
291                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
292                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
293                         return false;
294                 }
295                 boolean isAllowedEp = false;
296                 for (EPEndpoint ep : creds.getEndpoints()) {
297                         if (ep.getName().equals(uri)) {
298                                 isAllowedEp = true;
299                                 break;
300                         }
301                 }
302
303                 // If user doesn't specify any endpoint, allow all endpoints for that
304                 // account
305                 if (creds.getEndpoints().size() == 0)
306                         isAllowedEp = true;
307
308                 // Unauthorized access due to the invalid endpoints
309                 if (!isAllowedEp) {
310                         final String msg = "Unauthorized: Endpoint access denied";
311                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
312                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
313                         return false;
314                 }
315
316                 // Made it to the end!
317                 return true;
318         }
319
320         @SuppressWarnings("unused")
321         private String decrypted(String encrypted) throws Exception {
322                 String result = "";
323                 if (encrypted != null & encrypted.length() > 0) {
324                         try {
325                                 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
326                         } catch (Exception e) {
327                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
328                                 throw e;
329                         }
330                 }
331                 return result;
332         }
333
334         private String encrypted(String decryptedPwd) throws Exception {
335                 String result = "";
336                 if (decryptedPwd != null & decryptedPwd.length() > 0) {
337                         try {
338                                 result = CipherUtil.encryptPKC(decryptedPwd,
339                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
340                         } catch (Exception e) {
341                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
342                                 throw e;
343                         }
344                 }
345                 return result;
346         }
347
348         private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
349                 String[] path = portalApiPath.split("/");
350                 List<String> roleFunList = new ArrayList<>();
351                 if (path.length > 1) {
352                         roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
353                         if (roleFunList.size() >= 1) {
354                                 for (String roleFunction : roleFunList) {
355                                         String[] roleFunctionArray = roleFunction.split("/");
356                                         boolean b = true;
357                                         if (roleFunctionArray.length == path.length) {
358                                                 for (int i = 0; i < roleFunctionArray.length; i++) {
359                                                         if (b) {
360                                                                 if (!roleFunctionArray[i].equals("*")) {
361                                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
362                                                                         Matcher m = p.matcher(roleFunctionArray[i]);
363                                                                         b = m.matches();
364
365                                                                 }
366                                                         }
367                                                 }
368                                                         if (b)
369                                                                 return b;
370                                         }
371                                 }
372                         }
373                 } else {
374                         for (String roleFunction : roleFunctions) {
375                                 if (portalApiPath.matches(roleFunction))
376                                         return true;
377                         }
378                 }
379                 return false;
380         }
381
382         protected void handleSessionUpdates(HttpServletRequest request) {
383                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
384         }
385 }