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.nio.charset.Charset;
43 import java.util.ArrayList;
44 import java.util.Base64;
45 import java.util.List;
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.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;
85 public class PortalResourceInterceptor extends ResourceInterceptor {
87 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
90 private RemoteWebServiceCallService remoteWebServiceCallService;
93 private ManageService manageService;
96 AppsCacheService appCacheService;
99 private EPEELFLoggerAdvice epAdvice;
102 private BasicAuthenticationCredentialService basicAuthService;
104 private ExternalAccessRolesService externalAccessRolesService;
106 @SuppressWarnings("unchecked")
108 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
111 if (handler instanceof HandlerMethod) {
112 HandlerMethod method = (HandlerMethod) handler;
115 * These classes provide REST endpoints used by other application
116 * servers, NOT by an end user's browser.
118 if (method.getBean() instanceof FusionBaseController) {
119 FusionBaseController controller = (FusionBaseController) method.getBean();
120 if (!controller.isAccessible()) {
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];
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);
141 // check to see if roleFunctions of the user is in
143 // list of all role functions
144 // if not, ignore to prevent restricting every
146 // call; otherwise, if it is, then check for the
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(),
155 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
156 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
165 else if (method.getBean() instanceof BasicAuthenticationController) {
166 return checkBasicAuth(request, response);
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;
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();
180 } catch (Exception e) {
181 logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
183 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
184 throw new UrlAccessRestrictedException();
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();
197 handleSessionUpdates(request);
202 * Sets the status code and sends a response. Factors code out of many
206 * HttpServletResponse
208 * HTTP status code like 404
210 * Message to send in a JSON error object
212 private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
214 response.setStatus(statusCode);
215 response.setContentType("application/json");
216 response.getWriter().write("{\"error\":\"" + message + "\"}");
217 response.getWriter().flush();
221 * Gets HTTP basic authentication information from the request and checks
222 * whether those credentials are authorized for the request path.
227 * HttpServletResponse
228 * @return True if the request is authorized, else false
231 private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
232 String uri = request.getRequestURI().toString();
233 uri = uri.substring(uri.indexOf("/", 1));
235 final String authHeader = request.getHeader(EPCommonSystemProperties.AUTHORIZATION);
236 final String uebkey = request.getHeader(EPCommonSystemProperties.UEB_KEY);
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);
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);
254 if(uebkey !=null && !uebkey.isEmpty())
256 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
257 if (application == null) {
258 throw new Exception("Invalid uebkey!");
261 final String appUsername = application.getUsername();
262 final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
263 if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
270 BasicAuthCredentials creds;
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);
281 // Unauthorized access due to invalid credentials (username and
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);
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);
297 boolean isAllowedEp = false;
298 for (EPEndpoint ep : creds.getEndpoints()) {
299 if (ep.getName().equals(uri)) {
305 // If user doesn't specify any endpoint, allow all endpoints for that
307 if (creds.getEndpoints().size() == 0)
310 // Unauthorized access due to the invalid endpoints
312 final String msg = "Unauthorized: Endpoint access denied";
313 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
314 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
318 // Made it to the end!
322 @SuppressWarnings("unused")
323 private String decrypted(String encrypted) throws Exception {
325 if (encrypted != null && encrypted.length() > 0) {
327 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
328 } catch (Exception e) {
329 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
336 private String encrypted(String decryptedPwd) throws Exception {
338 if (decryptedPwd != null && decryptedPwd.length() > 0) {
340 result = CipherUtil.encryptPKC(decryptedPwd,
341 SystemProperties.getProperty(SystemProperties.Decryption_Key));
342 } catch (Exception e) {
343 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
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("/");
359 if (roleFunctionArray.length == path.length) {
360 for (int i = 0; i < roleFunctionArray.length; i++) {
362 if (!roleFunctionArray[i].equals("*")) {
363 Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
364 Matcher m = p.matcher(roleFunctionArray[i]);
376 for (String roleFunction : roleFunctions) {
377 if (portalApiPath.matches(roleFunction))
384 protected void handleSessionUpdates(HttpServletRequest request) {
385 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);