2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
7 * Modification Copyright (C) 2018 IBM.
8 * ===================================================================
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
15 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
28 * https://creativecommons.org/licenses/by/4.0/
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.
36 * ============LICENSE_END============================================
40 package org.onap.portalapp.portal.interceptor;
42 import java.util.ArrayList;
43 import java.util.HashMap;
44 import java.util.List;
45 import java.util.HashMap;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
49 import java.util.stream.Collectors;
51 import javax.servlet.http.HttpServletRequest;
52 import javax.servlet.http.HttpServletResponse;
54 import org.mockito.internal.stubbing.answers.ThrowsException;
55 import org.onap.aaf.cadi.CadiWrap;
56 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
57 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
58 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
59 import org.onap.portalapp.portal.controller.SharedContextRestController;
60 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
61 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
62 import org.onap.portalapp.portal.domain.EPApp;
63 import org.onap.portalapp.portal.domain.EPEndpoint;
64 import org.onap.portalapp.portal.domain.EPUser;
65 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
66 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
67 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
68 import org.onap.portalapp.portal.service.AdminRolesService;
69 import org.onap.portalapp.portal.service.AppsCacheService;
70 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
71 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
72 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
73 import org.onap.portalapp.portal.utils.EcompPortalUtils;
74 import org.onap.portalapp.service.RemoteWebServiceCallService;
75 import org.onap.portalapp.service.sessionmgt.ManageService;
76 import org.onap.portalapp.util.EPUserUtils;
77 import org.onap.portalsdk.core.controller.FusionBaseController;
78 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
79 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
80 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
81 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
82 import org.onap.portalsdk.core.onboarding.util.AuthUtil;
83 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
84 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
85 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
86 import org.onap.portalsdk.core.util.SystemProperties;
87 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
88 import org.springframework.beans.factory.annotation.Autowired;
89 import org.springframework.web.method.HandlerMethod;
91 public class PortalResourceInterceptor extends ResourceInterceptor {
93 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
96 private RemoteWebServiceCallService remoteWebServiceCallService;
99 private ManageService manageService;
102 AppsCacheService appCacheService;
105 private EPEELFLoggerAdvice epAdvice;
108 private AdminRolesService adminRolesService;
111 private BasicAuthenticationCredentialService basicAuthService;
113 @SuppressWarnings("unchecked")
115 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
118 if (handler instanceof HandlerMethod) {
119 HandlerMethod method = (HandlerMethod) handler;
122 * These classes provide REST endpoints used by other application
123 * servers, NOT by an end user's browser.
125 if (method.getBean() instanceof FusionBaseController) {
126 FusionBaseController controller = (FusionBaseController) method.getBean();
127 if (!controller.isAccessible()) {
129 // authorize portalApi requests by user role
130 String requestURI = request.getRequestURI();
131 if (requestURI != null) {
132 String[] uriArray = requestURI.split("/portalApi/");
133 if (uriArray.length > 1) {
134 String portalApiPath = uriArray[1];
136 Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
137 .getAttribute(SystemProperties
138 .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
139 Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
140 .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
141 // Defend against code error to avoid throwing NPE
142 if (roleFunctions == null || allRoleFunctions == null) {
143 logger.error(EELFLoggerDelegate.errorLogger,
144 "preHandle: failed to get role functions attribute(s) from session!!");
145 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
148 // check to see if roleFunctions of the user is in
150 // list of all role functions
151 // if not, ignore to prevent restricting every
153 // call; otherwise, if it is, then check for the
155 EPUser user = (EPUser) request.getSession().getAttribute(
156 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
157 //RoleAdmin check is being added because the role belongs to partner application
158 //inorder to access portal api's, bypassing this with isRoleAdmin Check
159 if ((EPUserUtils.matchRoleFunctions(portalApiPath, allRoleFunctions)
160 && !EPUserUtils.matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) {
161 logger.error(EELFLoggerDelegate.errorLogger,
162 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
164 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
165 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
174 else if (method.getBean() instanceof BasicAuthenticationController) {
175 return checkBasicAuth(request, response);
177 Object controllerObj = method.getBean();
178 if (controllerObj instanceof SessionCommunicationController
179 || controllerObj instanceof SharedContextRestController
180 || controllerObj instanceof ExternalAppsRestfulController) {
181 // check user authentication for RESTful calls
182 String secretKey = null;
184 epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
185 if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
186 request.getHeader("username"), request.getHeader("password"))) {
187 throw new UrlAccessRestrictedException();
189 } catch (Exception e) {
190 logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
192 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
193 throw new UrlAccessRestrictedException();
197 if (controllerObj instanceof WebAnalyticsExtAppController) {
198 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(EPCommonSystemProperties.UEB_KEY))) {
199 logger.error(EELFLoggerDelegate.errorLogger,
200 "preHandle: failed to verify app key for web analytics call");
201 throw new UrlAccessRestrictedException();
206 handleSessionUpdates(request);
211 * Sets the status code and sends a response. Factors code out of many
215 * HttpServletResponse
217 * HTTP status code like 404
219 * Message to send in a JSON error object
221 private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
223 response.setStatus(statusCode);
224 response.setContentType("application/json");
225 response.getWriter().write("{\"error\":\"" + message + "\"}");
226 response.getWriter().flush();
230 * Gets HTTP basic authentication information from the request and checks
231 * whether those credentials are authorized for the request path.
236 * HttpServletResponse
237 * @return True if the request is authorized, else false
240 private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
241 String uri = request.getRequestURI().toString();
242 uri = uri.substring(uri.indexOf("/", 1));
244 final String authHeader = request.getHeader(EPCommonSystemProperties.AUTHORIZATION);
245 final String uebkey = request.getHeader(EPCommonSystemProperties.UEB_KEY);
247 CadiWrap wrapReq = (CadiWrap) request;
248 logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the loop as the uri contains auxapi : {}");
249 String nameSpace=PortalApiProperties.getProperty(PortalApiConstants.AUTH_NAMESPACE);
250 logger.debug(EELFLoggerDelegate.debugLogger, "namespace form the portal properties : {}",nameSpace);
251 Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace, new HashMap<>());
252 logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed for the request and namespace : {}",accessallowed);
254 logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed is allowed: {}",accessallowed);
256 //String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
257 //check ueb condition
258 if(uebkey !=null && !uebkey.isEmpty())
260 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
261 if (application == null) {
262 throw new Exception("Invalid credentials!");
265 final String appUsername = application.getUsername();
266 logger.debug(EELFLoggerDelegate.debugLogger, "appUsername : {}",appUsername);
268 String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
269 logger.debug(EELFLoggerDelegate.debugLogger, "accountNamePassword : {}",accountNamePassword);
271 if (accountNamePassword == null || accountNamePassword.length != 2) {
272 final String msg = "failed to get username and password from Atuhorization header";
273 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth Username and password failed to get: {}", msg);
274 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
277 if (appUsername.equals(accountNamePassword[0])) {
280 final String msg = "failed to match the UserName from the application ";
281 logger.debug(EELFLoggerDelegate.debugLogger, "failed to match the UserName from the application checkBasicAuth Username and password failed to get: {}", msg);
282 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
291 final String msg = "no authorization found";
292 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth when no accessallowed: {}", msg);
293 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
298 }catch(ClassCastException e){
299 logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the classcastexception block if the UN is not the mechid : {}");
301 String secretKey = null;
302 // Unauthorized access due to missing HTTP Authorization request header
303 if (authHeader == null) {
304 if (remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
305 request.getHeader("username"), request.getHeader("password"))) {
308 final String msg = "no authorization found";
309 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
310 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
314 String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
315 if (accountNamePassword == null || accountNamePassword.length != 2) {
316 final String msg = "failed to get username and password from Atuhorization header";
317 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
318 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
322 if(uebkey !=null && !uebkey.isEmpty())
324 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
325 if (application == null) {
326 throw new Exception("Invalid credentials!");
329 final String appUsername = application.getUsername();
330 final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
331 if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
338 BasicAuthCredentials creds;
340 creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
341 accountNamePassword[1]);
342 } catch (Exception e1) {
343 logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e1);
344 final String msg = "Failed while getting basic authentication credential: ";
345 sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
349 // Unauthorized access due to invalid credentials (username and
351 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
352 final String msg = "Unauthorized: Access denied";
353 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
354 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
358 // Unauthorized access due to inactive account
359 if (creds.getIsActive().equals("N")) {
360 final String msg = "Unauthorized: The account is inactive";
361 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
362 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
366 }catch (Exception e2) {
367 logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials for some other exception", e2);
368 final String msg = "Failed while getting basic authentication credential for some other exception: ";
369 sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
377 @SuppressWarnings("unused")
378 private String decrypted(String encrypted) throws Exception {
380 if (encrypted != null && encrypted.length() > 0) {
382 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
383 } catch (Exception e) {
384 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
391 private String encrypted(String decryptedPwd) throws Exception {
393 if (decryptedPwd != null && decryptedPwd.length() > 0) {
395 result = CipherUtil.encryptPKC(decryptedPwd,
396 SystemProperties.getProperty(SystemProperties.Decryption_Key));
397 } catch (Exception e) {
398 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
405 protected void handleSessionUpdates(HttpServletRequest request) {
406 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);