ab88dd6e586aa47326430abeb0f847591218d6b3
[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.nio.charset.Charset;
43 import java.util.ArrayList;
44 import java.util.Base64;
45 import java.util.List;
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.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
55 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
56 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
57 import org.onap.portalapp.portal.controller.SharedContextRestController;
58 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
59 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
60 import org.onap.portalapp.portal.domain.EPApp;
61 import org.onap.portalapp.portal.domain.EPEndpoint;
62 import org.onap.portalapp.portal.domain.EPUser;
63 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
64 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
65 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
66 import org.onap.portalapp.portal.service.AppsCacheService;
67 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
68 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
69 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
70 import org.onap.portalapp.portal.utils.EcompPortalUtils;
71 import org.onap.portalapp.service.RemoteWebServiceCallService;
72 import org.onap.portalapp.service.sessionmgt.ManageService;
73 import org.onap.portalapp.util.EPUserUtils;
74 import org.onap.portalsdk.core.controller.FusionBaseController;
75 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
76 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
77 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
78 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
79 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
80 import org.onap.portalsdk.core.util.SystemProperties;
81 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
82 import org.springframework.beans.factory.annotation.Autowired;
83 import org.springframework.web.method.HandlerMethod;
84
85 public class PortalResourceInterceptor extends ResourceInterceptor {
86         
87         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
88
89         @Autowired
90         private RemoteWebServiceCallService remoteWebServiceCallService;
91
92         @Autowired
93         private ManageService manageService;
94         
95         @Autowired
96         AppsCacheService appCacheService;
97
98         @Autowired
99         private EPEELFLoggerAdvice epAdvice;
100
101         @Autowired
102         private BasicAuthenticationCredentialService basicAuthService;
103         @Autowired
104         private ExternalAccessRolesService externalAccessRolesService;
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                                                         if (matchRoleFunctions(portalApiPath, allRoleFunctions)
149                                                                         && !matchRoleFunctions(portalApiPath, roleFunctions)) {
150                                                                 EPUser user = (EPUser) request.getSession().getAttribute(
151                                                                                 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
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                 
238                 // Unauthorized access due to missing HTTP Authorization request header
239                 if (authHeader == null) {
240                         final String msg = "no authorization found";
241                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
242                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
243                         return false;
244                 }
245
246                 String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
247                 if (accountNamePassword == null || accountNamePassword.length != 2) {
248                         final String msg = "failed to get username and password from Atuhorization header";
249                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
250                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
251                         return false;
252                 }
253
254                 if(uebkey !=null && !uebkey.isEmpty())
255                 {
256                         EPApp application = appCacheService.getAppFromUeb(uebkey,1);
257                         if (application == null) {
258                                 throw new Exception("Invalid uebkey!");
259                         }
260                         else {
261                                 final String appUsername = application.getUsername();
262                                 final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
263                                 if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
264                                         return true;
265                                 }
266                         }
267                 }
268
269                 
270                 BasicAuthCredentials creds;
271                 try {
272                         creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
273                                         accountNamePassword[1]);
274                 } catch (Exception e) {
275                         logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
276                         final String msg = "Failed while getting basic authentication credential: ";
277                         sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
278                         throw e;
279                 }
280
281                 // Unauthorized access due to invalid credentials (username and
282                 // password)
283                 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
284                         final String msg = "Unauthorized: Access denied";
285                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
286                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
287                         return false;
288                 }
289
290                 // Unauthorized access due to inactive account
291                 if (creds.getIsActive().equals("N")) {
292                         final String msg = "Unauthorized: The account is inactive";
293                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
294                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
295                         return false;
296                 }
297                 boolean isAllowedEp = false;
298                 for (EPEndpoint ep : creds.getEndpoints()) {
299                         if (ep.getName().equals(uri)) {
300                                 isAllowedEp = true;
301                                 break;
302                         }
303                 }
304
305                 // If user doesn't specify any endpoint, allow all endpoints for that
306                 // account
307                 if (creds.getEndpoints().size() == 0)
308                         isAllowedEp = true;
309
310                 // Unauthorized access due to the invalid endpoints
311                 if (!isAllowedEp) {
312                         final String msg = "Unauthorized: Endpoint access denied";
313                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
314                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
315                         return false;
316                 }
317
318                 // Made it to the end!
319                 return true;
320         }
321
322         @SuppressWarnings("unused")
323         private String decrypted(String encrypted) throws Exception {
324                 String result = "";
325                 if (encrypted != null && encrypted.length() > 0) {
326                         try {
327                                 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
328                         } catch (Exception e) {
329                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
330                                 throw e;
331                         }
332                 }
333                 return result;
334         }
335
336         private String encrypted(String decryptedPwd) throws Exception {
337                 String result = "";
338                 if (decryptedPwd != null && decryptedPwd.length() > 0) {
339                         try {
340                                 result = CipherUtil.encryptPKC(decryptedPwd,
341                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
342                         } catch (Exception e) {
343                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
344                                 throw e;
345                         }
346                 }
347                 return result;
348         }
349
350         private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
351                 String[] path = portalApiPath.split("/");
352                 List<String> roleFunList = new ArrayList<>();
353                 if (path.length > 1) {
354                         roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
355                         if (roleFunList.size() >= 1) {
356                                 for (String roleFunction : roleFunList) {
357                                         String[] roleFunctionArray = roleFunction.split("/");
358                                         boolean b = true;
359                                         if (roleFunctionArray.length == path.length) {
360                                                 for (int i = 0; i < roleFunctionArray.length; i++) {
361                                                         if (b) {
362                                                                 if (!roleFunctionArray[i].equals("*")) {
363                                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
364                                                                         Matcher m = p.matcher(roleFunctionArray[i]);
365                                                                         b = m.matches();
366
367                                                                 }
368                                                         }
369                                                 }
370                                                         if (b)
371                                                                 return b;
372                                         }
373                                 }
374                         }
375                 } else {
376                         for (String roleFunction : roleFunctions) {
377                                 if (portalApiPath.matches(roleFunction))
378                                         return true;
379                         }
380                 }
381                 return false;
382         }
383
384         protected void handleSessionUpdates(HttpServletRequest request) {
385                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
386         }
387 }