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;
46 import java.util.regex.Matcher;
47 import java.util.regex.Pattern;
48 import java.util.stream.Collectors;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.servlet.http.HttpServletResponse;
53 import org.mockito.internal.stubbing.answers.ThrowsException;
54 import org.onap.aaf.cadi.CadiWrap;
55 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
56 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
57 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
58 import org.onap.portalapp.portal.controller.SharedContextRestController;
59 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
60 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
61 import org.onap.portalapp.portal.domain.EPApp;
62 import org.onap.portalapp.portal.domain.EPEndpoint;
63 import org.onap.portalapp.portal.domain.EPUser;
64 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
65 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
66 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
67 import org.onap.portalapp.portal.service.AdminRolesService;
68 import org.onap.portalapp.portal.service.AppsCacheService;
69 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
70 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
71 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
72 import org.onap.portalapp.portal.utils.EcompPortalUtils;
73 import org.onap.portalapp.service.RemoteWebServiceCallService;
74 import org.onap.portalapp.service.sessionmgt.ManageService;
75 import org.onap.portalapp.util.EPUserUtils;
76 import org.onap.portalsdk.core.controller.FusionBaseController;
77 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
78 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
79 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
80 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
81 import org.onap.portalsdk.core.onboarding.util.AuthUtil;
82 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
83 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
84 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
85 import org.onap.portalsdk.core.util.SystemProperties;
86 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
87 import org.springframework.beans.factory.annotation.Autowired;
88 import org.springframework.web.method.HandlerMethod;
90 public class PortalResourceInterceptor extends ResourceInterceptor {
92 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
95 private RemoteWebServiceCallService remoteWebServiceCallService;
98 private ManageService manageService;
101 AppsCacheService appCacheService;
104 private EPEELFLoggerAdvice epAdvice;
107 private AdminRolesService adminRolesService;
110 private BasicAuthenticationCredentialService basicAuthService;
112 @SuppressWarnings("unchecked")
114 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
117 if (handler instanceof HandlerMethod) {
118 HandlerMethod method = (HandlerMethod) handler;
121 * These classes provide REST endpoints used by other application
122 * servers, NOT by an end user's browser.
124 if (method.getBean() instanceof FusionBaseController) {
125 FusionBaseController controller = (FusionBaseController) method.getBean();
126 if (!controller.isAccessible()) {
128 // authorize portalApi requests by user role
129 String requestURI = request.getRequestURI();
130 if (requestURI != null) {
131 String[] uriArray = requestURI.split("/portalApi/");
132 if (uriArray.length > 1) {
133 String portalApiPath = uriArray[1];
135 Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
136 .getAttribute(SystemProperties
137 .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
138 Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
139 .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
140 // Defend against code error to avoid throwing NPE
141 if (roleFunctions == null || allRoleFunctions == null) {
142 logger.error(EELFLoggerDelegate.errorLogger,
143 "preHandle: failed to get role functions attribute(s) from session!!");
144 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
147 // check to see if roleFunctions of the user is in
149 // list of all role functions
150 // if not, ignore to prevent restricting every
152 // call; otherwise, if it is, then check for the
154 EPUser user = (EPUser) request.getSession().getAttribute(
155 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
156 //RoleAdmin check is being added because the role belongs to partner application
157 //inorder to access portal api's, bypassing this with isRoleAdmin Check
158 if ((EPUserUtils.matchRoleFunctions(portalApiPath, allRoleFunctions)
159 && !EPUserUtils.matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) {
160 logger.error(EELFLoggerDelegate.errorLogger,
161 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
163 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
164 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
173 else if (method.getBean() instanceof BasicAuthenticationController) {
174 return checkBasicAuth(request, response);
176 Object controllerObj = method.getBean();
177 if (controllerObj instanceof SessionCommunicationController
178 || controllerObj instanceof SharedContextRestController
179 || controllerObj instanceof ExternalAppsRestfulController) {
180 // check user authentication for RESTful calls
181 String secretKey = null;
183 epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
184 if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
185 request.getHeader("username"), request.getHeader("password"))) {
186 throw new UrlAccessRestrictedException();
188 } catch (Exception e) {
189 logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
191 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
192 throw new UrlAccessRestrictedException();
196 if (controllerObj instanceof WebAnalyticsExtAppController) {
197 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(EPCommonSystemProperties.UEB_KEY))) {
198 logger.error(EELFLoggerDelegate.errorLogger,
199 "preHandle: failed to verify app key for web analytics call");
200 throw new UrlAccessRestrictedException();
205 handleSessionUpdates(request);
210 * Sets the status code and sends a response. Factors code out of many
214 * HttpServletResponse
216 * HTTP status code like 404
218 * Message to send in a JSON error object
220 private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
222 response.setStatus(statusCode);
223 response.setContentType("application/json");
224 response.getWriter().write("{\"error\":\"" + message + "\"}");
225 response.getWriter().flush();
229 * Gets HTTP basic authentication information from the request and checks
230 * whether those credentials are authorized for the request path.
235 * HttpServletResponse
236 * @return True if the request is authorized, else false
239 private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
240 String uri = request.getRequestURI().toString();
241 uri = uri.substring(uri.indexOf("/", 1));
243 final String authHeader = request.getHeader(EPCommonSystemProperties.AUTHORIZATION);
244 final String uebkey = request.getHeader(EPCommonSystemProperties.UEB_KEY);
246 CadiWrap wrapReq = (CadiWrap) request;
247 logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the loop as the uri contains auxapi : {}");
248 String nameSpace=PortalApiProperties.getProperty(PortalApiConstants.AUTH_NAMESPACE);
249 logger.debug(EELFLoggerDelegate.debugLogger, "namespace form the portal properties : {}",nameSpace);
250 Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace, new HashMap<>());
251 logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed for the request and namespace : {}",accessallowed);
253 logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed is allowed: {}",accessallowed);
255 //String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
256 //check ueb condition
257 if(uebkey !=null && !uebkey.isEmpty())
259 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
260 if (application == null) {
261 throw new Exception("Invalid credentials!");
264 final String appUsername = application.getUsername();
265 logger.debug(EELFLoggerDelegate.debugLogger, "appUsername : {}",appUsername);
267 String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
268 logger.debug(EELFLoggerDelegate.debugLogger, "accountNamePassword : {}",accountNamePassword);
270 if (accountNamePassword == null || accountNamePassword.length != 2) {
271 final String msg = "failed to get username and password from Atuhorization header";
272 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth Username and password failed to get: {}", msg);
273 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
276 if (appUsername.equals(accountNamePassword[0])) {
279 final String msg = "failed to match the UserName from the application ";
280 logger.debug(EELFLoggerDelegate.debugLogger, "failed to match the UserName from the application checkBasicAuth Username and password failed to get: {}", msg);
281 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
290 final String msg = "no authorization found";
291 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth when no accessallowed: {}", msg);
292 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
297 }catch(ClassCastException e){
298 logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the classcastexception block if the UN is not the mechid : {}");
300 String secretKey = null;
301 // Unauthorized access due to missing HTTP Authorization request header
302 if (authHeader == null) {
303 if (remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
304 request.getHeader("username"), request.getHeader("password"))) {
307 final String msg = "no authorization found";
308 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
309 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
313 String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
314 if (accountNamePassword == null || accountNamePassword.length != 2) {
315 final String msg = "failed to get username and password from Atuhorization header";
316 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
317 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
321 if(uebkey !=null && !uebkey.isEmpty())
323 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
324 if (application == null) {
325 throw new Exception("Invalid credentials!");
328 final String appUsername = application.getUsername();
329 final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
330 if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
337 BasicAuthCredentials creds;
339 creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
340 accountNamePassword[1]);
341 } catch (Exception e1) {
342 logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e1);
343 final String msg = "Failed while getting basic authentication credential: ";
344 sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
348 // Unauthorized access due to invalid credentials (username and
350 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
351 final String msg = "Unauthorized: Access denied";
352 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
353 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
357 // Unauthorized access due to inactive account
358 if (creds.getIsActive().equals("N")) {
359 final String msg = "Unauthorized: The account is inactive";
360 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
361 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
365 }catch (Exception e2) {
366 logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials for some other exception", e2);
367 final String msg = "Failed while getting basic authentication credential for some other exception: ";
368 sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
376 @SuppressWarnings("unused")
377 private String decrypted(String encrypted) throws Exception {
379 if (encrypted != null && encrypted.length() > 0) {
381 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
382 } catch (Exception e) {
383 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
390 private String encrypted(String decryptedPwd) throws Exception {
392 if (decryptedPwd != null && decryptedPwd.length() > 0) {
394 result = CipherUtil.encryptPKC(decryptedPwd,
395 SystemProperties.getProperty(SystemProperties.Decryption_Key));
396 } catch (Exception e) {
397 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
404 protected void handleSessionUpdates(HttpServletRequest request) {
405 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);