Bulk upload changes and music health check apis
[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 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.BasicAuthenticationCredentialService;
65 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
66 import org.onap.portalapp.portal.utils.EcompPortalUtils;
67 import org.onap.portalapp.service.RemoteWebServiceCallService;
68 import org.onap.portalapp.service.sessionmgt.ManageService;
69 import org.onap.portalapp.util.EPUserUtils;
70 import org.onap.portalsdk.core.controller.FusionBaseController;
71 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
72 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
73 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
74 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
75 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
76 import org.onap.portalsdk.core.util.SystemProperties;
77 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
78 import org.springframework.beans.factory.annotation.Autowired;
79 import org.springframework.web.method.HandlerMethod;
80
81 public class PortalResourceInterceptor extends ResourceInterceptor {
82         private static final String APP_KEY = "uebkey";
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         private EPEELFLoggerAdvice epAdvice;
94
95         @Autowired
96         private BasicAuthenticationCredentialService basicAuthService;
97         @Autowired
98         private ExternalAccessRolesService externalAccessRolesService;
99
100         @SuppressWarnings("unchecked")
101         @Override
102         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
103                         throws Exception {
104
105                 if (handler instanceof HandlerMethod) {
106                         HandlerMethod method = (HandlerMethod) handler;
107
108                         /**
109                          * These classes provide REST endpoints used by other application
110                          * servers, NOT by an end user's browser.
111                          */
112                         if (method.getBean() instanceof FusionBaseController) {
113                                 FusionBaseController controller = (FusionBaseController) method.getBean();
114                                 if (!controller.isAccessible()) {
115
116                                         // authorize portalApi requests by user role
117                                         String requestURI = request.getRequestURI();
118                                         if (requestURI != null) {
119                                                 String[] uriArray = requestURI.split("/portalApi/");
120                                                 if (uriArray.length > 1) {
121                                                         String portalApiPath = uriArray[1];
122
123                                                         Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
124                                                                         .getAttribute(SystemProperties
125                                                                                         .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
126                                                         Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
127                                                                         .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
128                                                         // Defend against code error to avoid throwing NPE
129                                                         if (roleFunctions == null || allRoleFunctions == null) {
130                                                                 logger.error(EELFLoggerDelegate.errorLogger,
131                                                                                 "preHandle: failed to get role functions attribute(s) from session!!");
132                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
133                                                                 return false;
134                                                         }
135                                                         // check to see if roleFunctions of the user is in
136                                                         // the
137                                                         // list of all role functions
138                                                         // if not, ignore to prevent restricting every
139                                                         // trivial
140                                                         // call; otherwise, if it is, then check for the
141                                                         // access
142                                                         if (matchRoleFunctions(portalApiPath, allRoleFunctions)
143                                                                         && !matchRoleFunctions(portalApiPath, roleFunctions)) {
144                                                                 EPUser user = (EPUser) request.getSession().getAttribute(
145                                                                                 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
146                                                                 logger.error(EELFLoggerDelegate.errorLogger,
147                                                                                 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
148                                                                                 portalApiPath);
149                                                                 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
150                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
151                                                                 return false;
152                                                         } // failed to match
153
154                                                 } // is portalApi
155
156                                         } // requestURI
157                                 } // instance check
158                         } // not accessible
159                         else if (method.getBean() instanceof BasicAuthenticationController) {
160                                 return checkBasicAuth(request, response);
161                         }
162                         Object controllerObj = method.getBean();
163                         if (controllerObj instanceof SessionCommunicationController
164                                         || controllerObj instanceof SharedContextRestController
165                                         || controllerObj instanceof ExternalAppsRestfulController) {
166                                 // check user authentication for RESTful calls
167                                 String secretKey = null;
168                                 try {
169                                         epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
170                                         if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(APP_KEY),
171                                                         request.getHeader("username"), request.getHeader("password"))) {
172                                                 throw new UrlAccessRestrictedException();
173                                         }
174                                 } catch (Exception e) {
175                                         logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
176                                                         e);
177                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
178                                         throw new UrlAccessRestrictedException();
179                                 }
180                         }
181
182                         if (controllerObj instanceof WebAnalyticsExtAppController) {
183                                 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(APP_KEY))) {
184                                         logger.error(EELFLoggerDelegate.errorLogger,
185                                                         "preHandle: failed to verify app key for web analytics call");
186                                         throw new UrlAccessRestrictedException();
187                                 }
188                         }
189                 }
190
191                 handleSessionUpdates(request);
192                 return true;
193         }
194
195         /**
196          * Sets the status code and sends a response. Factors code out of many
197          * methods.
198          * 
199          * @param response
200          *            HttpServletResponse
201          * @param statusCode
202          *            HTTP status code like 404
203          * @param message
204          *            Message to send in a JSON error object
205          */
206         private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
207                         throws Exception {
208                 response.setStatus(statusCode);
209                 response.setContentType("application/json");
210                 response.getWriter().write("{\"error\":\"" + message + "\"}");
211                 response.getWriter().flush();
212         }
213
214         /**
215          * Gets HTTP basic authentication information from the request and checks
216          * whether those credentials are authorized for the request path.
217          * 
218          * @param request
219          *            HttpServletRequest
220          * @param response
221          *            HttpServletResponse
222          * @return True if the request is authorized, else false
223          * @throws Exception
224          */
225         private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
226                 String uri = request.getRequestURI().toString();
227                 uri = uri.substring(uri.indexOf("/", 1));
228
229                 final String authHeader = request.getHeader("Authorization");
230                 final String uebkey = request.getHeader("uebkey");
231                 
232                 // Unauthorized access due to missing HTTP Authorization request header
233                 if (authHeader == null) {
234                         final String msg = "no authorization found";
235                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
236                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
237                         return false;
238                 }
239
240                 String[] accountNamePassword = getUserNamePassword(authHeader);
241                 if (accountNamePassword == null || accountNamePassword.length != 2) {
242                         final String msg = "failed to get username and password from Atuhorization header";
243                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
244                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
245                         return false;
246                 }
247
248                 if(uebkey !=null && !uebkey.isEmpty())
249                 {
250                         List<EPApp> app = externalAccessRolesService.getApp(uebkey);
251                         EPApp application = null;
252                         if (app.isEmpty()) {
253                                 throw new Exception("Invalid uebkey!");
254                         }
255                         if (app.size() != 0 && !app.isEmpty()) {
256                                 application = app.get(0);
257                         }
258                         if (application != null) {
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         private String[] getUserNamePassword(String authValue) {
321                 String base64Credentials = authValue.substring("Basic".length()).trim();
322                 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
323                 final String[] values = credentials.split(":", 2);
324                 return values;
325         }
326
327         @SuppressWarnings("unused")
328         private String decrypted(String encrypted) throws Exception {
329                 String result = "";
330                 if (encrypted != null & encrypted.length() > 0) {
331                         try {
332                                 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
333                         } catch (Exception e) {
334                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
335                                 throw e;
336                         }
337                 }
338                 return result;
339         }
340
341         private String encrypted(String decryptedPwd) throws Exception {
342                 String result = "";
343                 if (decryptedPwd != null & decryptedPwd.length() > 0) {
344                         try {
345                                 result = CipherUtil.encryptPKC(decryptedPwd,
346                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
347                         } catch (Exception e) {
348                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
349                                 throw e;
350                         }
351                 }
352                 return result;
353         }
354
355         private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
356                 String[] path = portalApiPath.split("/");
357                 List<String> roleFunList = new ArrayList<>();
358                 if (path.length > 1) {
359                         roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
360                         if (roleFunList.size() >= 1) {
361                                 for (String roleFunction : roleFunList) {
362                                         String[] roleFunctionArray = roleFunction.split("/");
363                                         boolean b = true;
364                                         if (roleFunctionArray.length == path.length) {
365                                                 for (int i = 0; i < roleFunctionArray.length; i++) {
366                                                         if (b) {
367                                                                 if (!roleFunctionArray[i].equals("*")) {
368                                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
369                                                                         Matcher m = p.matcher(roleFunctionArray[i]);
370                                                                         b = m.matches();
371
372                                                                 }
373                                                         }
374                                                 }
375                                                         if (b)
376                                                                 return b;
377                                         }
378                                 }
379                         }
380                 } else {
381                         for (String roleFunction : roleFunctions) {
382                                 if (portalApiPath.matches(roleFunction))
383                                         return true;
384                         }
385                 }
386                 return false;
387         }
388
389         protected void handleSessionUpdates(HttpServletRequest request) {
390                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
391         }
392 }